44 Votes

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);
   KeyPreview := true;

In the OnKeyPress, you have to write the following code (the code #27 stands for ESC):

procedure TForm1.FormKeyPress(Sender: TObject; var Key: Char);
   if Key = #27 then Close;

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.

22 Votes

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

ReplyPositive Negative

About the Author

AvatarThe author has not added a profile short description yet.
Show Profile


Related Topics

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.


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