我想要显示对话框,当用户试图关闭应用程序(红色窗口十字和按钮在我的窗体),但当窗口关闭时,此对话框阻止关闭,所以我想要由应用程序检测何时窗口关闭,并继续没有对话框。以下是我的代码
在表单加载之后,我捕捉到了关闭事件:
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;
}
}
但当用户关闭应用程序时,对话框显示2次。第一个对话框不执行任何操作,第二个对话框之后执行操作。当windows关闭(因为windows正在等待我的应用程序关闭)时,我如何才能显示关闭对话框一次而没有对话框?
发布于 2013-01-23 16:49:24
编写此代码的更好方法(我的意见)是不订阅表单事件,而是使用可用的覆盖方法:
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,所以您不需要显式地设置它。
https://stackoverflow.com/questions/14484008
复制相似问题