Pages

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;

No comments:

Post a Comment

About the Author

I have more than 10 years of experience in IT industry. Linkedin Profile

I am currently messing up with neural networks in deep learning. I am learning Python, TensorFlow and Keras.

Author: I am an author of a book on deep learning.

Quiz: I run an online quiz on machine learning and deep learning.