Delphi: Quit program with ESC key
Tip by Delphian | Last update on 2021-06-28 | Created on 2012-06-11
In this tip, I would like to show you, how you can exit your Delphi or Lazarus application with a simple press on the escape key (ESC) on your keyboard.
In the OnCreate of the form, you have to write the following code, or alternatively, you can set KeyPreview in the Object Inspector to true.
procedure TForm1.FormCreate(Sender: TObject); begin KeyPreview := true; end;
In the OnKeyPress, you have to write the following code (the code #27 stands for ESC):
procedure TForm1.FormKeyPress(Sender: TObject; var Key: Char); begin if Key = #27 then Close; end;
One might think that the lower code snippet is sufficient, but this is not true. If you only write the lower code in your OnKeyPress, the program will only close if the window of your program has the focus. If one other element (for example, a Memo) has the focus, only the Memo receives the message of that the key was pressed and not the form.
But if we set KeyPreview to true, the form always gets a notification when a key is pressed before it is passed to the active element. And that is the only way to handle the ESC key event.
About the Author
The author has not added a profile short description yet.
Show Profile
Related Topics
Delphi: System-Wide HotKey
Tutorial | 1 Comment
Delphi/Lazarus: Is the ALT, SHIFT or CTRL key pressed?
Tutorial | 0 Comments
jQuery: Assign Action to Keyboard Keys (Keyboard Event)
Tip | 0 Comments
Delphi/Lazarus: Delete selected Items from ListBox using DEL-Key
Tip | 3 Comments
Delphi/Lazarus: Only allow Numbers in TEdit
Tip | 0 Comments
Delphi/Lazarus: Command Line Parameter Tutorial Part 1: Sending
Tutorial | 0 Comments
Windows: How to run a Program as Administrator - Once, Always or with Shortcut
Tutorial | 0 Comments
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.
Thanks a lot! I and many other amateur programmers have been looking for a simple solution to this simple problem for a long time.
It works perfectly.
2017-01-27 at 16:13