简体   繁体   English

关闭表格C#时,单击“是”两次。

[英]Click “yes” double when closing form C#?

I write a code for event close form C#. 我为事件关闭表单C#编写了代码。 It works, but when I click "yes" to close form I must click twice. 它有效,但是当我单击“是”以关闭表单时,我必须单击两次。 What wrong with it? 怎么了 And how can I fix this problem? 我该如何解决这个问题? Here is my code 这是我的代码

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
        DialogResult result = MessageBox.Show("Sure?", "Exit", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
        if (result == DialogResult.No)
        {
            Application.Exit();   
        }
        else
        {
            e.Cancel = true;
        }
    }

Your logic right now will run e.Cancel = true if you click yes, as in it cancels the closing. 如果单击“是”,您的逻辑现在将运行e.Cancel = true ,因为它取消了关闭。

Also, as mentioned in the comments, Application.Exit() is not necessary. 另外,如注释中所述,Application.Exit()不是必需的。

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    DialogResult result = MessageBox.Show("Sure?", "Exit", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
    if (result != DialogResult.Yes)
        e.Cancel = true;
}

A simpler version would be something like this: 一个更简单的版本是这样的:

 private void Form1_FormClosing(object sender, FormClosingEventArgs e)
 {
     e.Cancel = (MessageBox.Show("Sure?", 
                                 "Exit", 
                                 MessageBoxButtons.YesNo, 
                                 MessageBoxIcon.Question) == DialogResult.Yes);
 }

If the use clicks the Yes button, then e.Cancel will be set to true. 如果用户单击Yes按钮,则e.Cancel将设置为true。
If e.Cancel is set to true, the form will not close. 如果e.Cancel设置为true,该表单将不会关闭。
otherwise let the form closing sequence run it's course. 否则让表单关闭序列正常运行。

Calling the Application.Exit will trigger the FormClosing event again. 调用Application.Exit将再次触发FormClosing事件。 The solution is easier than you think: 该解决方案比您想象的要容易:

if (result == DialogResult.No)
    {
        e.Cancel = false; //It works as you expected 
    }
    else
    {
        e.Cancel = true;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM