Tuesday, 27 November 2012

Simple Delphi Program to Show Usage of OnCloseQuery Event in Delphi XE2

Simple Delphi Program to Show Usage of OnCloseQuery Event in Delphi XE2

Usage of OnCloseQuery Event:

OnCloseQuery Event occurs when close is attempted.

Use OnCloseQuery to specify the conditions under which the form can close. An OnCloseQuery event handler returns a Boolean CanClose value that determines whether a form is allowed to close. Its default value is true.

You can use an OnCloseQuery event handler to ask users if they are sure they really want the form closed immediately. For example, you can use the handler to display a message box that prompts the user to save a file before closing the form.

The TCloseQueryEvent type points to the method that determines whether a form can be closed. The value of the CanClose parameter determines if the form can close or not.

Requirement: When I close my delphi form by pressing cross/cancel red button on the top right corner of the delphi form or by pressing ALT + F4, I should get a confirmation message 'Do you really want to close the application?' If I press YES, then my delphi form should get closed otherwise nothing happens.

Solution: I will make a small function say 'CloseApplication' on the OnCloseQuery event of my delphi form. I will use MessageDlg asking for the confirmation to close the delphi application. Here is the simple delphi program which does all.

procedure MyForm.CloseApplication(Sender: TObject; var CanClose: Boolean);
var
  buttonSelected : integer;
begin
  buttonSelected := MessageDlg('Do you really want to close the application?',mtCustom, [mbYes,mbNo], 0);
  if buttonSelected = mrYES then
  begin
    CanClose := True;
  end
  else
  begin
    CanClose := False;
  end;
end;

4 comments:

  1. CanClose := buttonSelected = mrYES;

    ReplyDelete
    Replies
    1. Fails the code readability test! Use it, but don't pretend it's smarter.

      Delete
  2. CanClose := MessageDlg('Do you really want to close the application?',mtConfirmation, mbYesNo, 0) = mrYes;

    ReplyDelete
    Replies
    1. that's even sadder! all you're doing is exposing your laziness. Don't you know the compiler will rewrite the logic in the most efficient way. The "source code" is meant to be clean, easy to read, and make it easy for the programmer to deduce the structure and flow of it, especially if you have to go to Mars for a couple of years then come back to work on the same project... let alone if somebody else has to clean up your mess!

      Delete