当我按下表单上的X时,如何阻止消息框显示两次?仅供参考,但是按钮点击工作正常,这是提示我两次的X.
private void xGameForm_FormClosing(object sender, FormClosingEventArgs e)
{
//Yes or no message box to exit the application
DialogResult Response;
Response = MessageBox.Show("Are you sure you want to Exit?", "Exit", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
if (Response == DialogResult.Yes)
Application.Exit();
}
public void button1_Click(object sender, EventArgs e)
{
Application.Exit();
}
Run Code Online (Sandbox Code Playgroud)
在您进行Application.Exit调用时,表单仍处于打开状态(结束事件甚至尚未完成处理).Exit调用导致表单关闭.由于表单尚未关闭,因此它再次通过Closing路径并命中您的事件处理程序.
解决此问题的一种方法是记住实例变量中的决策
private bool m_isExiting;
private void xGameForm_FormClosing(object sender, FormClosingEventArgs e)
{
if ( !m_isExiting ) {
//Yes or no message box to exit the application
DialogResult Response;
Response = MessageBox.Show("Are you sure you want to Exit?", "Exit", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
if (Response == DialogResult.Yes) {
m_isExiting = true;
Application.Exit();
}
}
public void button1_Click(object sender, EventArgs e)
{
Application.Exit();
}
Run Code Online (Sandbox Code Playgroud)