c# - 在 CloseReason.UserClosing 表单上显示关闭对话框 2 次

标签 c# winforms

我想在用户尝试关闭应用程序时显示对话框(窗体上的红色窗口十字和按钮),但是当窗口关闭时,此对话框会阻止关闭,所以我想通过应用程序检测窗口何时关闭向下并继续,无需对话。这是我的代码

表单加载后我捕获关闭事件:

this.FormClosing += new FormClosingEventHandler(Form1_FormClosing);

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
        switch (e.CloseReason)
        {
            case CloseReason.UserClosing:
                if (MessageBox.Show("Do you want to exit the application?", "Your App", MessageBoxButtons.YesNo) == DialogResult.No)
                    {
                        e.Cancel = true;
                    }
                break;
            case CloseReason.WindowsShutDown:
                e.Cancel = false; //this is propably dumb
                break;
            default:
                break;
        }
    }

但是当用户关闭应用程序时,对话框会显示两次。第一个对话框不执行任何操作,第二个对话框后执行操作。 如何在 Windows 关闭时显示仅关闭一次的对话框而不显示对话框(因为 Windows 正在等待我的应用程序关闭)?

最佳答案

编写此代码的更好方法(我认为)是不订阅表单事件,而是使用可用的覆盖方法:

protected override void OnFormClosing(FormClosingEventArgs e)
{
  switch (e.CloseReason)
  {
    case CloseReason.UserClosing:
      if (MessageBox.Show("Do you want to exit the application?", "Your App", MessageBoxButtons.YesNo) == DialogResult.No)
      {
        e.Cancel = true;
      }
      break;
    case CloseReason.WindowsShutDown:
      e.Cancel = false; //this is propably dumb
      break;
    default:
      break;
    }

  base.OnFormClosing(e);
}

您可能需要考虑仅使用 if (e.CloseReason == CloseReason.UserClosing) 而不是基于当前形式的 switch 语句。 e.Cancel 默认情况下已经是 False,因此您不需要明确设置它。

关于c# - 在 CloseReason.UserClosing 表单上显示关闭对话框 2 次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14484008/

相关文章:

c# - 双重解析文化格式

c# - 在使用 C# 的 Visual Studio 2008 中,如何设置属性监视?

c# - 有没有办法跟踪数据上下文何时访问数据库?

c# vista 不允许访问应用程序数据文件夹

c# - 仅向管理员授予对特殊表单的访问权限

vb.net - 自定义属性未显示在属性窗口中

javascript - 模型数据有特殊字符(如 ' and ")”)需要以 HTML 形式显示

c# - 如何通过 ValueMember 选择 ListBox 项

c# - 如何在 Winform 中使用 TextBox 允许 ctrl+a?

vb.net - 使用 PrintDocument 和 HasMorePages 打印多页