在 OnCloseQuery 事件中使用 MessageDlg 时停止叮当声

0 delphi messagebox

我发现用户无意中点击了主窗体的系统菜单“X”并关闭了程序。

为了缓解这个问题,我添加了代码来询问用户是否确定要关闭该程序。这样做解决了人们在进行高压力事件签到时必须寻求重新启动程序的帮助。该计划全面获胜。

但是,每当我在主窗体的 OnCloseQuery 事件中使用 MessageDlg 函数时,都会发出烦人的“叮”声。

使用Delphi 10.4专业版

文件->新建->“Windows VCL应用程序-Delphi”将以下代码放入OnCloseQuery事件中

procedure TForm1.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
var
  iOkToClose: integer;
begin
  iOkToClose
    := MessageDlg('Do you wish to close the DertSQL program?',
                  mtConfirmation, [mbYes, mbNo], 0, mbNo);
  if iOkToClose <> mrYes then
    CanClose := FALSE
  else CanClose := TRUE;
end;
Run Code Online (Sandbox Code Playgroud)

编译运行程序然后戳系统菜单“X”

问:如何消除MessageDlg函数产生的“叮”声?

And*_*and 5

首先,我们只需要注意你的代码

if iOkToClose <> mrYes then
  CanClose := False
else
  CanClose := True
Run Code Online (Sandbox Code Playgroud)

写成更好

CanClose := iOkToClose = mrYes
Run Code Online (Sandbox Code Playgroud)

事实上,您甚至不需要该变量。您的整个事件处理程序可以简单地编写

CanClose :=
  MessageDlg(
    'Do you wish to close the DertSQL program?',
    mtConfirmation, [mbYes, mbNo], 0, mbNo
  ) = mrYes;
Run Code Online (Sandbox Code Playgroud)

现在,您听到的蜂鸣声与图标相关联,因此消除蜂鸣声的一种方法是删除图标:

CanClose :=
  MessageDlg(
    'Do you wish to close the DertSQL program?',
    TMsgDlgType.mtCustom, [mbYes, mbNo], 0, mbNo
  ) = mrYes;
Run Code Online (Sandbox Code Playgroud)

另外,在 VCL 中显示消息框的方法有很多种。

您当前正在使用该MessageDlg功能,我个人不太喜欢该功能。

一种替代方法是标准 Win32MessageBox函数:

CanClose :=
  MessageBox(
    Handle,
    'Do you want to close this application?',
    'My App',
    MB_ICONQUESTION or MB_YESNO
  ) = ID_YES;
Run Code Online (Sandbox Code Playgroud)

这里没有蜂鸣声。

但最好使用任务对话框:

var dlg := TTaskDialog.Create(Self);
try
  dlg.Caption := 'My App';
  dlg.Title := 'Do you want to exit the application?';
  dlg.MainIcon := tdiNone;
  dlg.CommonButtons := [tcbYes, tcbNo];
  CanClose := dlg.Execute and (dlg.ModalResult = mrYes);
finally
  dlg.Free;
end;
Run Code Online (Sandbox Code Playgroud)

这特别好,因为您随后可以使用蓝色的主要指令来遵循 Win32 UI 指南:

确认任务对话框的屏幕截图

但正如您所看到的,这是很多代码。您可能想根据任务对话框制作自己的消息对话框功能,就像我在任务对话框消息框中所做的那样:

CanClose := TD('Do you want to exit the application?')
  .YesNo
  .Execute(Self) = mrYes;
Run Code Online (Sandbox Code Playgroud)