[英]Give me a hint on FormClosing event
I have a MainForm. 我有一个MainForm。 I can close it by using a close button (upper right corner) or by clicking a menuitem miExit.
我可以使用关闭按钮(右上角)或单击菜单项miExit将其关闭。
My problem is when I clicked miExit and answered "OK", it shows messageBox TWICE . 我的问题是,当我单击miExit并回答“确定”时,它显示messageBox TWICE 。 How can I fix it ?
我该如何解决? (I understand why it shows twice but how can I avoid it ?)
(我知道为什么它会显示两次,但如何避免呢?)
Both formclosing and miExit clicks must provide messagebox with "Exit ?" 关闭和单击miExit都必须在消息框中提供“退出?” prompt.
提示。
partial class MainForm : Form
{
void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
DialogResult dr = MessageBox.Show("Exit ?", "Exit", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
if (dr == DialogResult.OK)
{
SaveSettings();
}
else
{
e.Cancel = true;
}
}
void miExit_Click(object sender, EventArgs e)
{
DialogResult dr = MessageBox.Show("Exit ?", "Exit", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
if (dr == DialogResult.OK)
{
SaveSettings();
Application.Exit();
}
}
void SaveSettings()
{
// save user settings to file ...
}
}
将miExit_Click
事件处理程序更改miExit_Click
都不做,只能调用Close
,然后让FormClosing
处理程序以关闭方式进行处理。
Change the miExit_Click
handlier to just call Application.Exit()
更改
miExit_Click
handlier只是调用Application.Exit()
Application.Exit()
automatically calls the FormClosing
event on all open forms. Application.Exit()
自动在所有打开的窗体上调用FormClosing
事件。 And yes, these forms can cancel the Exit by setting their FormClosingEventArgs
's Cancel
property to true
. 是的,这些表单可以通过将其
FormClosingEventArgs
的Cancel
属性设置为true
来取消退出。
PS If you don't believe me, I linked to the documentation for Application.Exit()
, the FormClosing
bit is the first bullet point under Remarks. PS:如果您不相信我,我会链接到
Application.Exit()
的文档, FormClosing
位是“备注”下的第一个要点。
Apply DRY here. 在这里申请干 。 You have redundant code for Form Close.
您有多余的代码用于窗体关闭。
http://en.wikipedia.org/wiki/Don 't_repeat_yourself http://en.wikipedia.org/wiki/Don't_repeat_yourself
Replace the contents of miExit_Click with 'this.Close();' 将miExit_Click的内容替换为“ this.Close();”。 which will in turn call MainForm_FormClosing so you don't need that code twice.
依次调用MainForm_FormClosing,因此您不需要两次该代码。 Job done
任务完成
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.