![](/img/trans.png)
[英]c# WinForms form still closes after setting e.Cancel = true in Form_FormClosing event
[英]C# Dialog keeps pop up when click yes in Form_FormClosing
在我的 C# winForms 中添加一个事件FormClosing
但添加代码Close()
后对话框不断弹出
private void AdminPanel_FormClosing(object sender, FormClosingEventArgs e)
{
DialogResult result = (MessageBox.Show(this,
"Are you sure you want to close the Application?",
"Exit",
MessageBoxButtons.YesNo, MessageBoxIcon.Question));
if (result == DialogResult.Yes)
{
//dialog keeps poping up when i try to close the form
Close();
}
else {
e.Cancel = true;
}
}
您是否尝试过删除Close();
称呼? 您已经在Closing
事件处理程序中——除非您取消关闭,否则无论如何它都会发生。
您不需要在FormClosing
中添加对Close
方法的调用,因为您已经处于 Application 的表单关闭调用模式中。
你需要写:
private void AdminPanel_FormClosing(object sender, FormClosingEventArgs e)
{
var result = MessageBox.Show(this,
"Are you sure you want to close the Application?",
"Exit",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) );
if ( result != DialogResult.Yes )
{
e.Cancel = true;
}
}
如果DialogResult.Yes
那么它对e.Cancel
没有任何作用并且表单被关闭并且FormClosed
事件被调用。
如果e.Cancel
设置为true
,则应用程序管理器会取消Close
调用,并且不会调用FormClosed
。
如果您在FormClosing
中添加对Close
的调用,则会出现堆栈溢出:只要您单击Yes
,该框就会显示并显示并显示并显示和显示等等,除非您单击No
...
如果您想强制应用程序结束,您可以在FormClosed
事件中使用:
Environment.Exit(0);
但也许你有什么东西可以阻止关闭。
您在FormClosed
中有代码吗? 它会抛出异常吗? 否则你需要抓住它,因为它会停止关闭。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.