如何提示用户确认程序退出?

How to prompt user to confirm program exit?

我正在尝试做我的问题所说的,当用户点击表单上的关闭按钮时,我想提示用户确认,这是我想出的代码......它是有问题,当我点击关闭按钮时,它确实提示我确认,但程序还是关闭了,与我点击的按钮无关,我做错了什么?

procedure TfrmLogin.FormClose(Sender: TObject; var Action: TCloseAction);
begin
  if MessageDlg('Are you sure you want to exit?', mtWarning, [tMsgDlgBtn.mbYes, tMsgDlgBtn.mbCancel], 0) = 0 then
    begin
      Application.Terminate;
    end;
end;

当您为 TForm.OnClose 阅读 the documentation 时,您一定错过了 table 告诉您可以在 Action 参数中输入的内容:

The TCloseEvent type points to a method that handles the closing of a form. The value of the Action parameter determines if the form actually closes. These are the possible values of Action:

caNone

The form is not allowed to close, so nothing happens.

caHide

The form is not closed, but just hidden. Your application can still access a hidden form.

caFree

The form is closed and all allocated memory for the form is freed.

caMinimize

The form is minimized, rather than closed. This is the default action for MDI child forms.

因此,你可以做到

procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);
begin
  if MessageBox(Handle, 'Do you want to close this app?', 'Super App', MB_YESNOCANCEL) = ID_YES then
    Action := caHide
  else
    Action := caNone;
end;

但可以说使用 OnCloseQuery 事件更好:

procedure TForm1.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
  CanClose := MessageBox(Handle, 'Do you want to close this app?', 'Super App', MB_YESNOCANCEL) = ID_YES;
end;