【问题标题】:Double confirmation on exit退出时双重确认
【发布时间】:2011-01-07 02:36:09
【问题描述】:

我正在尝试让用户被提示确认退出我在 c# 中的程序,但由于某种原因,如果他们说“是”他们想退出,确认框会再次弹出。我不知道为什么。

    if (MessageBox.Show("Are you sure you want to exit?", "Confirm exit", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
    {
        e.Cancel = true;
    }
    else { Application.Exit(); }

【问题讨论】:

  • 这段代码在哪里运行?
  • 我假设您正在处理表单关闭事件。我认为您不需要 Application.Exit()
  • 是的,表单关闭,但我确实需要 application.exit(),因为我需要同时关闭另一个窗口。
  • 在你的Application.Run()中,你传入的是哪个表单?
  • StartupWindow(),正在关闭的窗口是 BackupWindow()。如果其中一个关闭,我需要它们都关闭,所以我发现最简单的方法是简单地使用 Application.Exit()。

标签: c# winforms exit confirm


【解决方案1】:

使用这个

 private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
    {
        if (MessageBox.Show("Are you sure you want to close?", "Infomate", MessageBoxButtons.YesNo) == DialogResult.No)
        {
            e.Cancel = true;
        }        
    }

【讨论】:

    【解决方案2】:

    啊,你检查CloseReason 的FormClosing 事件了吗?我认为你可能会因为两个不同的原因得到相同的事件(尽管我并不完全期望这会正常发生);检查您的FormClosingEventArgs 以查看参数是什么。

    【讨论】:

      【解决方案3】:

      啊,我想出了如何解决它。我删除了 Application.Exit(); FormClosing 事件中的事件,并将其移至 FormClosed 事件中。现在一切正常。

      【讨论】:

      • 我遇到了和你一样奇怪的问题,你的回答完美地解决了它。
      【解决方案4】:

      作为 SFD,他说您需要使用消息框创建事件。如果用户关闭表单和警告消息框,我添加了过滤器:

          private void close_confirmation(object sender, FormClosingEventArgs e)
          {
              if (e.CloseReason == CloseReason.FormOwnerClosing)
              {
                  if (MessageBox.Show("Are you sure you want to close?", "Application", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.No)
                  {
                      e.Cancel = true;
                  }
              }
          }
      

      您需要将事件分配给表单以使其工作:

      this.FormClosing += new FormClosingEventHandler(close_confirmation);
      

      如果你想让它停止以便用户可以再次关闭窗口而不显示消息:

      this.FormClosing -= close_confirmation;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-10-01
        • 1970-01-01
        • 2019-03-12
        • 2011-04-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多