How to Trap Keystrokes in the Form Instead of Form's ControlsLast reviewed: June 21, 1995Article ID: Q99688 |
The information in this article applies to:
- Standard and Professional Editions of Microsoft Visual Basic for Windows, versions 2.00 and 3.00
SUMMARYTo trap most keystrokes (see NOTE below) at the form level instead of passing them to the form's controls, set the form's KeyPreview property to True and use KeyAscii=0 in the Form_KeyPress event. This prevents keystrokes from going to the form's controls. NOTE: the technique described in this article will not intercept the ENTER key on command buttons. Command buttons are subclassed Windows push button controls and the ENTER key is an accelerator key that is passed to the superclass; Visual Basic never receives it. Also note that KeyCode=0 in the Form_KeyDown event won't prevent keystrokes going to the form's controls. This behavior is by design.
MORE INFORMATIONA form's KeyPreview property determines whether form keyboard events are invoked before control keyboard events. The keyboard events are KeyDown, KeyUp, and KeyPress. You can use the KeyPreview property to create a keyboard-handling procedure for a form. For example, when an application uses function keys, it's likely that you'll want to process the keystrokes at the form level rather than writing code for each control that might receive keystroke events. If a form has no visible and enabled controls, it automatically receives all keyboard events. To handle keyboard events only at the form level and not allow controls to receive keyboard events, set KeyAscii to 0 in the form's KeyPress event.
Using Form_KeyPress Versus Form_KeyDown to Prevent Text Box InputThis example demonstrates the difference between Form_KeyPress and Form_KeyDown to attempt to trap and prevent all keyboard input for a text box.
To prevent the Text1 box from accepting input, add KeyAscii = 0 to the Form_KeyPress event of Form1. This traps and disables all input to all the controls on the form, as desired. The Form_KeyPress event enables you to handle the keystrokes the way you want.
|
Additional reference words: 2.00 3.00
© 1998 Microsoft Corporation. All rights reserved. Terms of Use. |