C# 表单关闭时的消息框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12417504/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 23:12:16  来源:igfitidea点击:

MessageBox on Form Closing

c#formclosing

提问by Federal09

I'm use this code for question before closing the application, but it is not working correctly.
My code is as below.

我在关闭应用程序之前使用此代码进行提问,但它无法正常工作。
我的代码如下。

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
   DialogResult dlgresult = MessageBox.Show("Exit or no?",
                               "My First Application",
                               MessageBoxButtons.YesNo,
                               MessageBoxIcon.Information);
   if (dlgresult == DialogResult.No)
   {
      e.Cancel = true;

   }
   else
   {
     Application.Exit();
   }
}

采纳答案by Turbot

You don't need to explicitly call Application.Exit()since you are in the FormClosingevent which means the Closing request has been triggered(e.g. click on the cross at the form button, this.Close()). You just need to intercept the closing request and indicate e.Cancel = true;

您不需要显式调用,Application.Exit()因为您处于FormClosing事件中,这意味着关闭请求已被触发(例如,单击表单按钮上的十字架,this.Close())。您只需要拦截关闭请求并指出e.Cancel = true;

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    if(MessageBox.Show("Exit or no?",
                       "My First Application",
                        MessageBoxButtons.YesNo,
                        MessageBoxIcon.Information) == DialogResult.No) {
        e.Cancel = true;
    }
}