KeyPreviewProperty (Delphi)

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, and so on).

Code

var
  FormColor: TColor;

procedure TForm1.FormCreate(Sender: TObject);
begin
  KeyPreview := True;
  FormColor := Form1.Color;
end;

procedure TForm1.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
  if Key = VK_F1 then
  begin
    Form1.Color := clAqua;
    if (ComboBox1.Text = 'KeyDown') then
      ComboBox1.Text := 'KeyDown2'
    else
      ComboBox1.Text := 'KeyDown';
    WriteLn(ComboBox1.Text);
  end;
end;

procedure TForm1.FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
  if Key = VK_F1 then
  begin
    Form1.Color := FormColor;
    if (ComboBox1.Text = 'KeyUp') then
      ComboBox1.Text := 'KeyUp2'
    else
      ComboBox1.Text := 'KeyUp';
    WriteLn(ComboBox1.Text);
  end;
end;

Uses

Personal tools
Assistance