16 16 Votes

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

Info by SmartUser | Last Update on 07/03/2018 | Created on 29/03/2013

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);
var
  msg: String;
begin
  msg:='You have not saved. Do you really want to close?';

  if MessageDlg(msg, 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 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.

ReplyPositiveNegative

About the Author

Avatar AuthorThe author has not added a short description to his profile yet.
Show Profile | Message

 

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.

Participate

Ask your own question or write your own articles on askingbox.com. How to do.