How to allow or disallow program shutdown in Delphi

posted 15 Mar 2010, 14:50 by Delphi Basics
An example of trapping the closing of a program for example a user might accidentally try to maximize a form and close it instead, without saving their work ...

Make a change to the first edit box and then attempt to shut down the program, and a demo of a messagebox appears asking for confirmation and listing choices for possible actions you can also implement similar code yourself in a buttonclick event handler for an 'Exit' button (using 'Apllication.Terminate'). Remember to double click the event handler in the Object Inspector for the form's OnCloseQuery event and the Edit Box 'OnChange' event to initialize the event handlers.

unit Unit1;
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
  TForm1 = class(TForm)
  Edit1: TEdit;
  Edit2: TEdit;
  procedure Edit1Change(Sender: TObject);
  procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
  { Private declarations }
  { Public declarations }
  Form1: TForm1;
{$R *.DFM}
procedure TForm1.Edit1Change(Sender: TObject);
  Form1.Tag := 1;
{the var variable 'CanClose controls whether or not the user can shut
down the program, its default value is true}
procedure TForm1.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
 TheAnswer : Word;
  If Form1.Tag <> 0 then
  begin {the text in Edit box was changed}
   TheAnswer := MessageDlg('Save changes?', mtConfirmation,
   [mbYes, mbNo, mbCancel], 0);
   If TheAnswer = mrCancel then CanClose := false; {return to program}
   If TheAnswer = mrYes then {save the file routine}
   Edit2.Text := Edit1.Text; {in otherwords do the save here}
   {if the answer was no, since canclose defaults to true
   just let the program close}
Possible MessageDlg Return value constants ­ Word
these return values indicate which button was pushed on the Dialog
these values correspond to the button type which is declared using
mb instead of mr ie mbOk pressed would return mrOk
mrNone mrAbort mrYes mrOk mrRetry mrNo mrCancel mrIgnore mrAll
the following constants indicate what type of dialog icon will appear
and the caption on the dialog and are in the second field TMsgDlgType
mtWarning A message box containing a yellow exclamation point symbol.
mtError A message box containing a red stop sign.
mtInformation A message box containing a blue "i".
mtConfirmation A message box containing a green question mark.
mtCustom A message box containing no bitmap.
The caption of the message box
is the name of the application's executable file.