【问题标题】:Why when choosing No it's asking twice?为什么选择否时它会询问两次?
【发布时间】:2017-02-08 17:30:33
【问题描述】:
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (MessageBox.Show("Are you sure you want to exist ?",
                        "Are you sure you want to exist ?",
                        MessageBoxButtons.YesNo,
                        MessageBoxIcon.Information) == DialogResult.No)
            {
                e.Cancel = true;
                Application.Exit();
            }
        }

如果我单击“是”,它就存在。但是,如果我单击否,则消息会再次显示,并且仅在第二次否生效时显示。

我有一个后台工作者和一个我更新的richTextView。 e.Cancel = true 和 application.exit 就够了吗?

【问题讨论】:

  • 您不想关闭它,但又想关闭它。下定决心。
  • "您确定要存在吗?"天哪,这太苛刻了。
  • 所以你问用户是否想退出,如果他们说“不”,那么你还是退出? (即通过Application.Exit();)?
  • 在代码中设置断点并单步执行会发生什么?这不是揭示了真正发生的事情吗?
  • And i have a backgroundworker and a richTextView that i update

标签: c# .net winforms


【解决方案1】:

您的逻辑不正确,您需要执行其中一项操作,而不是同时执行这两项操作,具体取决于所选择的内容。

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    if (MessageBox.Show("Are you sure you want to exit ?",
                "Are you sure you want to exit ?",
                MessageBoxButtons.YesNo,
                MessageBoxIcon.Information) == DialogResult.No)
    {
      e.Cancel = true; // cancels the close action
    }
    else
      Application.Exit(); // closes the app, this might not be necessary. Just proceeding with the form close is enough UNLESS this is not the main application form

}

【讨论】:

  • 我认为Application.Exit() 根本没有必要。显然Form 已经关闭了。
  • @RenéVogt - 除非它不是主应用程序表单。我将它添加到 cmets 以澄清。
【解决方案2】:

如果选择“否”,则使用e.Cancel = true; 取消当前的FormClosing 事件。
但是你还是打电话给Application.Exit();。所以Form 再次关闭,FormClosing 再次引发。

删除Application.Exit() 行,一切正常。

【讨论】:

    猜你喜欢
    • 2010-10-13
    • 1970-01-01
    • 2021-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-29
    • 1970-01-01
    相关资源
    最近更新 更多