KeyPress Event

Occurs when the user presses and releases a key.

PROCEDURE Object.KeyPress
LPARAMETERS [nIndex,] nKeyCode, nShiftAltCtrl

Parameters

You must include an LPARAMETERS or PARAMETERS statement in the event procedure and specify a name for each parameter.

  • nIndex
    Uniquely identifies a control if it is in a control array.

  • nKeyCode
    Contains a number which identifies the key pressed. For a list of codes for special keys and key combinations, see INKEY( ).

  • nShiftAltCtrl
    Sets a bit if a modifier key is held down while the key identified in nKeyCode is pressed.

    The valid modifier keys are the SHIFT, CTRL, and ALT keys.

    The values returned in nShiftAltCtrl for individual modifier keys are listed in the following table.

    Modifier key values for nShiftAltCtrl

    Key Value
    SHIFT 1
    CTRL 2
    ALT 4

    This parameter is the sum of the bits, with the least-significant bits corresponding to the SHIFT key (bit 0), the CTRL key (bit 1), and the ALT key (bit 2 ).

    These bits correspond to the values 1, 2, and 4, respectively. This parameter indicates the state of these keys. Some, all, or none of the bits can be set, indicating that some, all, or none of the keys is pressed. For example, if both CTRL and ALT are pressed, the value of nShiftAltCtrl is 6.

Remarks

The object with the focus receives the event.

A form can receive the KeyPress event in three special cases:

  • The form contains no controls, or none of its controls is visible and enabled.
  • The form's KeyPreview property is set to true (.T.). The form receives the KeyPress event first and then the control with focus receives the event.
  • If a control on the form cannot process a keystroke (for example, when Tab is pressed to move the focus to the next control).

A KeyPress event is useful for intercepting keystrokes entered in a control. It enables you to immediately test keystrokes for validity or to format characters as they are typed. Use the KeyPreview property to create global keyboard-handling routines.

The KeyPress event does not occur for any combination of keys with the ALT key.

See Also

INKEY( ) | KeyPreview Property

Applies To: CheckBox | ComboBox | CommandButton | EditBox | Form | ListBox | OptionButton | Spinner | TextBox