3

When my form is closed by clicking on 'Cross Button' or Alt + F4, I want user to ask whether he wants to close the application or not. If yes, I will terminate the application otherwise nothing to do. I am using following code on the onclose event of the form

procedure MyForm.FormClose(Sender: TObject; var Action: TCloseAction);
var
  buttonSelected : integer;
begin
  buttonSelected := MessageDlg('Do you really want to close the application?',mtCustom, [mbYes,mbNo], 0);
  if buttonSelected = mrYES then
  begin
    Application.Terminate;
  end
  else
  begin
    //What should I write here to resume the application
  end;

end;

Whether I click Yes or No, my application is terminating. What should I do so that on No click of confirmation box, my application should not terminate. How should I improve my above function? Am I using right form event to implement this functionality? Please help..

  • 2
    You would have to use `Action` parameter, but it's better task for the `OnCloseQuery` event. – TLama Nov 27 '12 at 09:49
  • 1
    If that's your main form, then you don't need to call `Application.Terminate`. The application will go down once the main form is closed. – David Heffernan Nov 27 '12 at 09:54
  • I hate when an application asks if I was really quite sure of I wanted it be gone. – Sertac Akyuz Nov 27 '12 at 09:56
  • @sertacAkyuz - But its the requirement –  Nov 27 '12 at 10:02
  • @DavidHeffernan - okay, removed application.terminate –  Nov 27 '12 at 10:02
  • Please also answer my this question http://stackoverflow.com/questions/13559156/unexpected-behaviour-of-ttable-and-tdbgrid-in-delphi-xe2 –  Nov 27 '12 at 10:07

2 Answers2

9

The Window will stay open if you type

Action := caNone;

in your else Part

Obl Tobl
  • 5,604
  • 8
  • 41
  • 65
9
procedure TForm1.FormCloseQuery(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;

or as @TLama advised, to simplify:

procedure TForm1.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
  CanClose := MessageDlg('Do you really want to close the application?', mtCustom, [mbYes, mbNo], 0) = mrYES;
end;
AvgustinTomsic
  • 1,809
  • 16
  • 22
  • 4
    You can also simplify this to one line `CanClose := MessageDlg('Do you really want to close the application?', mtCustom, [mbYes, mbNo], 0) = mrYES;`. – TLama Nov 27 '12 at 10:27