Visual Basic Reference

KeyPress Event

See Also    Example    Applies To

Occurs when the user presses and releases an ANSI key.

Syntax

Private Sub Form_KeyPress(keyasciiAs Integer)

Private Subobject_KeyPress([indexAs Integer,]keyasciiAs Integer)

The KeyPress event syntax has these parts:

Part Description
object An object expression that evaluates to an object in the Applies To list.
index An integer that uniquely identifies a control if it's in a control array.
keyascii An integer that returns a standard numeric ANSI keycode. Keyascii is passed by reference; changing it sends a different character to the object. Changing keyascii to 0 cancels the keystroke so the object receives no character.

Remarks

The object with the focus receives the event. A form can receive the event only if it has no visible and enabled controls or if the KeyPreview property is set to True. A KeyPress event can involve any printable keyboard character, the CTRL key combined with a character from the standard alphabet or one of a few special characters, and the ENTER or BACKSPACE key. A KeyPress event procedure is useful for intercepting keystrokes entered in a TextBox or ComboBox control. It enables you to immediately test keystrokes for validity or to format characters as they're typed. Changing the value of the keyascii argument changes the character displayed.

You can convert the keyascii argument into a character by using the expression:

Chr(KeyAscii)

You can then perform string operations and translate the character back to an ANSI number that the control can interpret by using the expression:

KeyAscii = Asc(char)

Use KeyDown and KeyUp event procedures to handle any keystroke not recognized by KeyPress, such as function keys, editing keys, navigation keys, and any combinations of these with keyboard modifiers. Unlike the KeyDown and KeyUp events, KeyPress doesn't indicate the physical state of the keyboard; instead, it passes a character.

KeyPress interprets the uppercase and lowercase of each character as separate key codes and, therefore, as two separate characters. KeyDown and KeyUp interpret the uppercase and lowercase of each character by means of two arguments: keycode, which indicates the physical key (thus returning A and a as the same key), and shift, which indicates the state of shift+key and therefore returns either A or a.

If the KeyPreview property is set to True, a form receives the event before controls on the form receive the event. Use the KeyPreview property to create global keyboard-handling routines.

Note   The ANSI number for the keyboard combination of CTRL+@ is 0. Because Visual Basic recognizes a keyascii value of 0 as a zero-length string (""), avoid using CTRL+@ in your applications.