Use the OnKeyDown event handler to specify special processing to occur when a key is pressed. The OnKeyDown handler can respond to keyboard keys, including function keys and keys combined with the Shift, Alt, and Ctrl keys, and pressed mouse buttons.

The Key parameter is the key on the keyboard. For non-alphanumeric keys, use virtual key codes to determine the key pressed. For more information, see Virtual Key codes.

The Shift parameter indicates whether the Shift, Alt, or Ctrl keys are combined with the keystroke.

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.

/*
This example changes a form’s color to aqua when the user
presses the F1 key, even when a control on the form has the
focus. When the user releases the key, the form returns to
its original color. Set the KeyPreview on the form to True.
Set the OnKeyDown event to FormKeyDown and set the OnKeyUp
event to FormKeyUp. Set the KeyPreview on the form to True.
Behavior is dependent on keyboard driver(USB, serial, etc).
*/void__fastcall TForm1::FormKeyDown(TObject *Sender, WORD &Key,
TShiftState Shift)
{
if (Key == VK_F1)
{
FormColor = Form1->Color;
Form1->Color = clAqua;
if (ComboBox1->Text == "KeyDown")
ComboBox1->Text = "KeyDown2";
else
ComboBox1->Text = "KeyDown";
Form1->Refresh();
Memo1->Lines->Add(ComboBox1->Text);
}
}
void__fastcall TForm1::FormKeyUp(TObject *Sender, WORD &Key, TShiftState Shift)
{
if (Key == VK_F1)
{
Form1->Color = FormColor;
if (ComboBox1->Text == "KeyUp")
ComboBox1->Text = "KeyUp2";
else
ComboBox1->Text = "KeyUp";
Form1->Refresh();
Memo1->Lines->Add(ComboBox1->Text);
}
}