Close program with ESC key in Delphi

Posted on May 30, 2018 at 11:22 am

You can allow the user to quit your application using the ESC key in your Delphi application. To do so, first you need to set KeyPreview to true eighter in the Object Inspector or by adding the following code in the OnCreate event of the form:

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

Then write the following code in the OnKeyPress event (#27 stands for ESC):

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

By setting also KeyPreview to true, the form will always get a notification when a key is pressed, before it is passed to the active element. Else your application will be closed with the ESC key only if the window of your application has the focus.

Receive updates via email

Other Posts

Updated Posts