22 Votes

Delphi: Capture keystroke anywhere in the program

Question by Chematik | 2012-05-28 at 23:16

I have written a program in Delphi, in which I want to run some commands when the user presses a key. Therefore, I use the following procedure in the OnKeyPress of my form to capture the key press:

procedure TForm1.FormKeyPress(Sender: TObject; var Key: Char);
begin
   if key = 'a' then ...;
   if key = 'b' then ...;
   if key = 'c' then ...;
end;

However, this does not work at any time. Sometimes the function is executed, sometimes it is as if the button was never pressed. Does anyone know, what to do and how I can achieve a program-wide keypress?

ReplyPositiveNegative
3Best Answer5 Votes

Your procedure is invoked only when the focus of the program is on the main form. As soon as something else (such as a Button or a ComboBox) has the focus, the keypress only comes to this component, but not to the main form and your procedure.

Just set the property KeyPreview of your form to true, or write this in the OnCreate of your form:

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

This makes, that the keystroke first will be sent to the main program, so that it can be captured there.
2012-05-30 at 12:19

ReplyPositive Negative
Reply

Related Topics

Delphi: System-Wide HotKey

Tutorial | 1 Comment

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.