1919 Votes

Delphi/Lazarus: Show "Do you really want to close?" dialog before closing the form

Info by Stefan Trost | Last update on 2023-01-19 | Created on 2013-03-29

If a user has not saved his inputs, his changements or his other work in an application and is about to close the program or the corresponding window, sometimes it is wanted to show a dialog like "You have not saved your changes. Do you really want to close this program?". In this tutorial, I would like to show you how to realize such a message box with Delphi or Lazarus.

We implement the display of our dialog in the OnCloseQuery event of our form. For that, we click on the form and we set the appropriate procedure from the Object Inspector. OnCloseQuery is executed each time before the form will be closed and in this procedure, we can influence whether the form should really be closed.

Our OnCloseQuery procedure might look something like that:

procedure TForm1.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
var
  AMsg: String;
begin
  AMsg := 'You have not saved your changes. Do you really want to close?';

  if MessageDlg(AMsg, mtConfirmation, [mbOk, mbCancel], 0) = mrCancel then 
    CanClose := false;
end; 

If we set the variable CanClose to false within the OnCloseQuery event, the window will not be closed and the user comes back to the program. We show the user a message dialog, in which the user can click on "OK" (close) or "Cancel" (not close). In the case, the dialog returns "mrCancel", we know that the user has clicked "Cancel" and we can set CanClose to form and bring the user back to the program.

Check for Changes

Of course, this code can be improved respectively expanded in a way that the message is only shown if changes have actually been made and these have not yet been saved.

For that, you can create a global variable (for example you can name it "isSaved"), which is initialized with "true" and is set to" false" with every change. As soon as the user saves the changes, the variable is set back to "true" and the game starts again with the first changes. Then, in OnCloseQuery, we can check whether the variable is "false" or "true" and we can only show the dialog in the case, that the variable is "false" and the user really has not saved his changes yet.

ReplyPositiveNegative

About the Author

AvatarYou can find Software by Stefan Trost on sttmedia.com. Do you need an individual software solution according to your needs? - sttmedia.com/contact
Show Profile

 

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.