See Also Example
Applies To
Form, check box
Description
Occurs when the user presses and releases an ANSI
Syntax
Sub Form_KeyPress (KeyAscii As Integer)
Sub control_KeyPress ([Index As Integer,]KeyAscii As Integer)
Remarks
The KeyPress event uses these arguments:
Argument Description
Index Uniquely identifies a control if it is in a control array .
KeyAscii 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 that the object receives no character.
The object with the focus A form can receive the event only if it has no visible and enabled controls, or if the KeyPreview property is 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 text box or combo box. It allows you to immediately test keystrokes for validity or to format characters as they are typed. Changing the value of the argument KeyAscii changes the character displayed.
You can convert the argument KeyAscii 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 understand by using the expression:
KeyAscii = Asc(char)
Use KeyDown and KeyUp Unlike the KeyDown and KeyUp events, KeyPress does not indicate the physical state of the keyboard; instead, it passes a character.
KeyPress interprets the uppercase and lowercase of each character as separate keycodes 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 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 null string, you should avoid using Ctrl+@ in your applications.
Help:
ANSI Table
Asc Function
Change Event
Chr, Chr$ Function
Keyboard
KeyPreview Property
SendKeys Statement
Programmer's Guide:
Chapter 3, "Creating and Using Controls"
The example converts text entered into a text box to uppercase. To try this example, paste the code into the Declarations section of a form that contains a text box. Then press F5 and type something into the text box.
Sub Text1_KeyPress (KeyAscii As Integer)
Char = Chr(KeyAscii)
KeyAscii = Asc(UCase(Char))
End Sub