KeyPress Event - Event Procedures

KeyPress Event — Event Procedures

See Also         Example

To create an event procedure that runs when the KeyPress event occurs, set the OnKeyPress property to [Event Procedure], and click the Build button .

Syntax

Private Sub Form_KeyPress(KeyAscii As Integer)

Private Sub controlname_KeyPress(KeyAscii As Integer)

The KeyPress event has the following arguments.

Argument Description
controlname The name of the control whose KeyPress event procedure you want to run.
KeyAscii Returns a numeric ANSI key code. The KeyAscii argument is passed by reference; changing it sends a different character to the object. Setting the KeyAscii argument to 0 cancels the keystroke so that the object doesn't recognize that a key was pressed.

Remarks

A KeyPress event procedure is useful for intercepting keystrokes entered in a text box or combo box. It enables you to 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 to a character by using the following expression.

Chr(KeyAscii)

You can then perform string operations and translate the character back to an ANSI number that the control can recognize by using the following syntax.

KeyAscii = Asc(character)

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

You can respond to specific keys pressed while a form is open, regardless of which control has the focus. For example, you may want the key combination CTRL+X to always perform the same action on a form. To make sure a form receives all keyboard events, even those that occur for controls, before they occur for the controls, set the KeyPreview property of the form to Yes. With this property setting, all keyboard events occur first for the form, and then for the control that has the focus. You can respond to specific keystrokes in the form's KeyDown, KeyPress, and KeyUp events. You can prevent a control from receiving keystrokes you've responded to, and prevent the keyboard events from occurring for the control, by setting the KeyCode argument to 0 for both the KeyDown and KeyUp events, and setting the KeyAscii argument to 0 for the KeyPress event. You must set all three arguments to 0 if you don't want the control to receive the keystrokes.

You can use the arguments for the KeyDown, KeyPress, and KeyUp events, in conjunction with the arguments for the MouseDown, MouseUp, and MouseMove events, to make your application work smoothly for both keyboard and mouse users.

You can't cancel the KeyPress event in an event procedure, but you can cancel it in a macro.