Keyboard events

Keyboard Events

KeyPress, KeyUp, KeyDown :-

KeyPress :

Occurs when a key is pressed while the control has focus. KeyPress event occurs (fires or executes or happens) every time a key is pressed.

argument have two properties (KeyChar & Handled).

The KeyChar property returns the character corresponding to the key pressed. Set Handled property to true to cancel the KeyPress event.

Example 1 : ‘To allow only alphabets (A to Z or a to z or backspace(8) or spacebar(32) or enter(13))

Private Sub TextBox5_KeyPress(ByVal sender As Object, ByVal e As
System.Windows.Forms.KeyPressEventArgs) Handles TextBox5.KeyPress
 If (Asc(e.KeyChar) >= 65 And Asc(e.KeyChar) <= 90) Or (Asc(e.KeyChar) >= 97 And
 Asc(e.KeyChar) <= 122) Or Asc(e.KeyChar) = 8 Or Asc(e.KeyChar) = 32 Or
 Asc(e.KeyChar) = 13 Then
e.Handled = False
 Else
e.Handled = True
 End If
End Sub 

Example 2 : ‘ To allow only NUMBERS ( 0 to 9) or Backspace(8)

Private Sub TextBox6_KeyPress(ByVal sender As Object, ByVal e As
System.Windows.Forms.KeyPressEventArgs) Handles TextBox6.KeyPress
If (Asc(e.KeyChar) >= 48 And Asc(e.KeyChar) <= 57) Or Asc(e.KeyChar) = 8 Then
e.Handled = False
Else
 e.Handled = True
End If
End Sub

KeyDown :

The KeyDown event occurs (fires or executes or happens)when the user presses any key.

KeyUp :

The KeyUp event occurs (fires or executes or happens)when the user releases the key).

With each KeyDown& KeyUp event, it returns an argument, which has six properties (KeyCode, Handled, Modifiers, Alt, Control, Shift).

Leave a Comment