OnKeyPress Event

Occurs while the object has focus and a key is pressed and released.

Syntax

Object.OnKeyPress ( pnKeyAscii )

The OnKeyPress event syntax has the following parts:

 

Name

Type

Description

Object

An object

A control or the AForm object

pnKeyAscii

Var Short, as enumAKey

A key code, such as aKeyF1 (the F1 key), aKeyA (the A key), or aKeyHome (the HOME key).

Where

enumAKey can be one of the keys on the keyboard. See enumAKey for a list of the keys.

Comments

pnKeyAscii is passed by reference. Changing it sends a different character to the object. Changing pnKeyCode to 0 cancels the keystroke so that the object receives no character. Use the OnKeyDown event if you need to change behavior of navigation keys, ENTER or ESC, this is event is used for printable characters such as 'A'..

OnKeyPress can be used to validate or filter the key which has been pressed. For example, to allow only numeric keys for number entries.

Example

The following example will check for a valid numeric key entry:

chk1.OnKeyPress(pnKeyAscii)

{

if pnKeyAscii=aKey0 Or pnKeyAscii=aKey1 Or pnKeyAscii=aKey2 Or pnKeyAscii=aKey3 Or pnKeyAscii=aKey4 Or pnKeyAscii=aKey5 Or pnKeyAscii=aKey6 Or pnKeyAscii=aKey7 Or pnKeyAscii=aKey8 Or pnKeyAscii=aKey9

!....  perform necessary processing

else

! display an error message and return for corrected entry

MsgBox("a numeric key is required - please try again")

endif

}

! This example checks in a form's OnKeyPress event:
 

if form.f_bViewOnly

 if nKeyAscii=aKeyEscape

  unload form

 endif

endif

Applies to

 

AButton

AListBox

ASwitch

ACheckBox

ARadioButton

ATextBox

AComboBox

AScrollBar

 

AForm

ASlider

 

See Also

OnKeyDown, OnKeyUp