Visual Basic Concepts

Visual Studio 6.0

The KeyPress Event

The KeyPress event occurs when any key that corresponds to an ASCII character is pressed. The ASCII character set represents not only the letters, digits, and punctuation on a standard keyboard but also most of the control keys. The KeyPress event only recognizes the ENTER, TAB, and BACKSPACE keys, however. The other function, editing, and navigation keys can be detected by the KeyDown and KeyUp events.

Use the KeyPress event whenever you want to process the standard ASCII characters. For example, if you want to force all the characters in a text box to be uppercase, you can use this event to change the case of the keys as they are typed:

Private Sub Text1_KeyPress (KeyAscii As Integer)
   KeyAscii = Asc(UCase(Chr(KeyAscii)))
End Sub

The keyascii argument returns an integer value corresponding to an ASCII character code. The procedure above uses Chr to convert the ASCII character code into the corresponding character, UCase to make the character uppercase, and Asc to turn the result back into a character code.

Using the same ASCII character codes, you can test whether a key recognized by the KeyPress event is pressed. For instance, the following event procedure uses KeyPress to detect if the user is pressing the BACKSPACE key:

Private Sub Text1_KeyPress (KeyAscii As Integer)
   If KeyAscii = 8 Then MsgBox "You pressed the _
      BACKSPACE key."
End Sub

You can also use the Visual Basic key-code constants in place of the character codes. The BACKSPACE key in the example above has an ASCII value of 8. The constant value for the BACKSPACE key is vbKeyBack.

For More Information   For a complete list of character codes, see "Character Set (0–127)" and "Character Set (128–255)" in the Language Reference. A complete list of key code constants with corresponding ASCII values is available in "Key Code Constants" or by using the Object Browser and searching for KeyCodeConstants.

You can also use the KeyPress event to alter the default behavior of certain keys. For example, pressing ENTER when there is no Default button on the form causes a beep. You can avoid this beep by intercepting the ENTER key (character code 13) in the KeyPress event.

Private Sub Text1_KeyPress (KeyAscii As Integer)
   If KeyAscii = 13 Then KeyAscii = 0
End Sub
Show: