Question

messagebox (handle, 'do you really want to exit?', 'are you sure?', 1);

in this button there are two things, what the user can do. ok and cancel. what code do i have to write, that the button closes the program at "ok" and ends the dialog, when pressing cancel?

Was it helpful?

Solution

Delphi provides better solutions for showing a messagebox. I should use the MessageDlg function. The return value of the MessageDlg (and MessageBox) function indicates the users choice. So you when you place a yes button on the MessageDlg, the return value will be mrYes when the user presses the Yes button. So your code would be like this:

var
  ShouldClose: Boolean;
begin
  if MessageDlg('Do you really want to quit?', mtConfirmation, 
      [mbYes, mbNo], 0) = mrYes then
    ShouldClose := True
  else
    ShouldClose := False;
end;

You also want to close your application if the users chooses Yes. When you have a normal Delphi VCL application you can implement the CloseQuery event of you mainform, the CloseQuery event is executed when you try to close your mainform (like clicking the closebutton) and has a variable CanClose. Setting CanClose to True means the MainForm is OK to close, setting it to false will prevent your mainform from closing:

procedure TForm1.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
  CanClose := MessageDlg('Do you really want to quit?', mtConfirmation, 
    [mbYes, mbNo], 0) = mrYes;
end;

OTHER TIPS

First, make sure that the buttons in the message box match the text. So if the text is "Do you really want to exit?" then the buttons should be "Yes" and "No".

Second, use the appropriate constants, so that your code is easier to read later on. That would be:

var
  Res: integer;

Res := Application.MessageBox('Do you really want to exit?', 'Are you sure?',
  MB_ICONQUESTION or MB_YESNO);

The result will then be either IDYES or IDNO. So assuming that the call is inside a method of your main form, you would use it like:

if Res = IDYES then
  Close;

If you call this from another place, you could also call

if Res = IDYES then
  Application.Terminate;

Edit: Please do also check out the Vista User Inteface Guidelines on dialog boxes which state:

Unnecessary confirmations are annoying

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top