1818 Votes

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

Info by SmartUser | Last update on 2018-03-07 | Created on 2013-03-29

If the user has not saved his work and is about to close the application or the appropriate form, sometimes it is wanted to show a dialog like "You have not saved. Do you really want to close this program?". In this info, I would like to show you how to realize such a message box with Delphi.

We define 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 might look something like that:

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

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

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 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.

Of course, you can improve this code in the way that the dialog is only shown when the user actually has unsaved changes. For that, you can create a global variable which will be set to false whenever the user makes changes and to true whenever the user saves the changes. Then, in OnCloseQuery, we can look whether the variable is false and true and we can only show the dialog in the case, the variable is false and the user actually has not saved his changes yet.


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.