KeyPreview Property

See Also2BBA1AL                 Example1JMQZLL>Low

Applies To



Determines whether form keyboard events are invoked before control keyboard events.  The keyboard events are KeyDown, KeyUpRI06O6, and KeyPressPFFDUA.


[form.]KeyPreview[ = { True|False} ]


The KeyPreview property settings are:

Setting             Description


True                 The form receives keyboard events first, then the active control receives keyboard events.

False                (Default) The active control receives keyboard events; the form does not.



You can use this property to create a keyboard-handling procedure for a form.  For example, when an application uses function keys, 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, and set KeyCode to 0 in the form's KeyDown event.

Data Type

IntegerDOKXHY (Boolean)

See Also


KeyDown, KeyUp EventsRI06O6

KeyPress EventPFFDUA


Programmer's Guide:

Chapter 3 "Creating and Using Controls"

KeyPreview Property Example

The example creates a form keyboard handler in the KeyDown event.  Each of the first four function keys presents a different message.  To try this example, paste the code into the Declarations section of a form.  Then press F5.  Once the program is running, press any one of the first four function keys.

' Values from CONSTANT.TXT.
Const KEY_F1 = &H70
Const KEY_F2 = &H71
Const KEY_F3 = &H72
Const KEY_F4 = &H73

Sub Form_Load ()
  KeyPreview = True
End Sub

Sub Form_KeyDown (KeyCode As Integer, Shift As Integer)
  Select Case KeyCode
    Case KEY_F1: MsgBox "F1 is your friend."
    Case KEY_F2: MsgBox "F2 could copy text."
    Case KEY_F3: MsgBox "F3 could paste text."
    Case KEY_F4: MsgBox "F4 could format text."
  End Select
End Sub