KeyPreview (C++)

From RAD Studio Code Examples
Jump to: navigation, search

Description

This example changes a form's color to aqua when you press the F1 key, even when a control on the form has the focus. When you release the key, the form returns to its original color. Set the KeyPreview on the form to True. Set the OnKeyDown event to FormKeyDown and the OnKeyUp event to FormKeyUp. Set the KeyPreview on the form to True. Behavior is dependent on keyboard driver (USB, serial, etc).

Code

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);
  }
}

Uses