留言箱的一般问题

时间:2009-02-09 11:53:34

标签: delphi messagebox

messagebox(句柄,'你真的想退出吗?','你确定吗?',1);

在这个按钮中有两件事,用户可以做什么。好的,取消。 我必须编写什么代码,按钮在“确定”时关闭程序并在按下取消时结束对话框?

2 个答案:

答案 0 :(得分:3)

首先,确保消息框中的按钮与文本匹配。所以,如果文字是“你真的想退出吗?”然后按钮应为“是”和“否”。

其次,使用适当的常量,以便以后更容易阅读代码。那将是:

var
  Res: integer;

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

结果将是IDYES或IDNO。因此,假设调用位于主窗体的方法中,您可以使用它:

if Res = IDYES then
  Close;

如果您从其他地方拨打此电话,也可以拨打

if Res = IDYES then
  Application.Terminate;

修改:请查看Vista User Inteface Guidelines on dialog boxes哪个州:

  

不必要的确认令人讨厌

答案 1 :(得分:2)

Delphi为显示消息框提供了更好的解决方案。 我应该使用MessageDlg函数。 MessageDlg(和MessageBox)函数的返回值表示用户的选择。因此,当您在MessageDlg上放置“是”按钮时,当用户按下“是”按钮时,返回值将为mrYes。 所以你的代码就像这样:

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

如果用户选择“是”,您还需要关闭应用程序。 如果你有一个普通的Delphi VCL应用程序,你可以实现mainform的CloseQuery事件,当你尝试关闭你的mainform(比如单击关闭按钮)并且有一个CanClose变量时,会执行CloseQuery事件。将CanClose设置为True意味着MainForm可以关闭,将其设置为false将阻止主窗体关闭:

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