RAD Studio VCL Reference
TCheckBox.OnKeyPress Event

Occurs when a key is pressed.

property OnKeyPress: TKeyPressEvent;
__property TKeyPressEvent OnKeyPress;

Use the OnKeyPress event handler to make something happen as a result of a single character key press.  

The Key parameter in the OnKeyPress event handler is of type Char; therefore, the OnKeyPress event registers the ASCII character of the key pressed. Keys that don't correspond to an ASCII Char value (Shift or F1, for example) don't generate an OnKeyPress event. Key combinations (such as Shift+A), generate only one OnKeyPress event (for this example, Shift+A results in a Key value of "A" if Caps Lock is off). To respond to non-ASCII keys or key combinations, use the OnKeyDown or OnKeyUp event handlers. 

An application gets Windows WM_KEYDOWN messages for all keys when the user presses a key. These messages indirectly fire the OnKeyDown event. If you set the Key to 0 there you prevent only any further processing of this message. But for keys that generate characters Windows also produces WM_CHAR. At the time your OnKeyDown event fires, the WM_CHAR message for the key will already be in the message queue. Setting Key to 0 does not stop it from being delivered, so it fires the OnKeyPress event. You must set the Key to #0 to prevent the control from intercepting the WM_CHAR message.  

This method of organizing key processing has advantages. Code that only deals with characters, including control characters like #13 for carriage return, #3 for Ctrl-C and so on, should go into the OnKeyPress event. Code that deals with keys that do not generate characters should be put into the OnKeyDown event.  

C++ Examples: 


This event handler displays a message dialog box specifying
which key was pressed:

void __fastcall TForm1::FormKeyPress(TObject *Sender, char &Key)
  char keyString[25];
  keyString[0] = Key;
  strcpy(&keyString[1], " Was Pressed");
  TMsgDlgButtons() << mbOK;
  MessageDlg(AnsiString(keyString), TMsgDlgType(mtInformation), TMsgDlgButtons() << mbOK, 0);


Delphi Examples: 

This event handler displays a message dialog box specifying
which key was pressed:
procedure TForm1.FormKeyPress(Sender: TObject; var Key: Char);
  MessageDlg(Key + ' has been pressed', mtInformation, [mbOK], 0)


Copyright(C) 2009 Embarcadero Technologies, Inc. All Rights Reserved.
What do you think about this topic? Send feedback!