我想在用户尝试关闭应用程序时显示对话框(窗体上的红色窗口十字和按钮),但是当窗口关闭时,此对话框会阻止关闭,所以我想通过应用程序检测窗口何时关闭向下并继续,无需对话。这是我的代码
表单加载后我捕获关闭事件:
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/