a bug in the richtextbox.textlength fuction

  • Thread starter Thread starter rs
  • Start date Start date
R

rs

I am trying to override the keypress fucntion in a form as the following

Private Sub rtbInput_KeyPress(ByVal sender As Object, ByVal e As
System.Windows.Forms.KeyPressEventArgs) Handles rtbInput.KeyPress

If (e.KeyChar = Chr(13) And rtbInput.TextLength = 1) Then

Beep()

rtbInput.Clear()

ElseIf (rtbInput.TextLength = 0) Then

cmdEnter.Enabled = False

ElseIf rtbInput.TextLength > 0 Then

cmdEnter.Enabled = True

ElseIf e.KeyChar = Chr(13) Then

cmdEnter_Click(sender, e)

End If

End Sub

textlength fuction does not return the right number of chars in the
rtbinput. am doing something wrong?
 
Hi you first have to understand what keypress handles:
if you use the keypress, when you press a key the event handler will be
raised but the key (letter/number/or anything else) hasn't yet been send to
the richtextbox. So if I type the letter 'b' in the keypress event the
textlength of the richtextbox is still 0 because it hasn't yet received the
letter. If you use the keyup you handle the richtextbox after it has
received the key, so I think that's why you think the .textlength function
is incorrect.
I also changed the textlength = 2 in you first check because else it only
would catch a return/enter keypress if the textbox was empty because a
return/enter also counts as textlength 1. I also changed
cmdEnter_Click(sender, e) to call enter_click which is a different sub so
from your cmdEnter clickevent you should also call enter_clcik cause this is
the better way to do it when you want to use a piece of code multiple times.

hth Peter

Private Sub rtb_KeyUp(ByVal sender As Object, ByVal e As _
System.Windows.Forms.KeyEventArgs) Handles rtb.KeyUp
If (e.KeyCode = Keys.Return AndAlso rtb.TextLength = 2) Then
Beep()
rtb.Clear()
ElseIf (rtb.TextLength = 0) Then
cmdEnter.Enabled = False
ElseIf rtb.TextLength > 0 Then
cmdEnter.Enabled = True
ElseIf e.KeyCode = Keys.Enter Then
Call enter_click()
End If
End Sub

Private Sub enter_click()
End Sub
 
Back
Top