View contents of this chapter

Handling Keyboard

Windows passes special keyboard events to your applications so they can monitor the keyboard events. These events are the keyPress, keyDown, key Up events. You can test for keystrokes when a keyboard event occurs.

Play Sound Keystroke testing is useful for validating input and playing games.

The KeyPress event occurs when users press any key that corresponds with one of these characters.

  • Uppercase and lowercase letters
  • Numeric digits
  • Punctuation
  • Enter, Tab, and Backspace

You can use the KeyPress to determine exactly which key users pressed.

An event is associated with an object, such as a command button, text box, etc. The KeyPress event associates with the currently selected object. If no object has the focus, this event is associated with the form.

The KeyPress event tests for most ASCII characters, but doesn't test for all ASCII characters, such as, horizontal tab, arrow keys, and other special control related characters that appear between ASCII values 0 to 31. If you were to write a KeyPress event for a Text Box, the event procedure might began and end like this.

Private Sub Text1_KeyPress (KeyAscii as Integer)
    'Code goes here
End Sub

The KeyDown event occurs whenever users press a key. Therefore, both the KeyDown and KeyPress events can occur at the same time. The KeyDown event is more complicated than the KeyPress event. The KeyDown event returns the same value for uppercase and lowercase letters. It also returns the state of the Shift key.

Private Sub Text1_KeyDown(KeyCode As Integer, Shift As Integer)
    'Code goes here
End Sub

KeyCode contains the keystroke and the shift argument determines the state of the control keys such as Shift, Ctrl, and Alt.



© Universal Teacher Publications        INDEX Previous Screen Next Screen