2010-06-01 97 views
1

当我按表格 上的X时,如何停止显示消息框两次?仅供参考,butoon点击工作正常,这是X提示我两次。为什么Application.Exit提示我两次?

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(); 
    } 

回答

5

在点你做出Application.Exit电话形式仍然是开放的(closing事件甚至还没有完成处理)。退出呼叫导致表单被关闭。由于表单尚未关闭,因此再次通过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(); 
    } 
+0

由于它的伟大工程 – 2010-06-01 15:57:06

+0

那岂不是更简单的只是取消退出,如果用户实际点击没有?否则,用户确认他希望退出,那么就像我已经看到的那样,没有其他事情要做,因为它已经关闭了它的应用程序。另外,还有一个可读性优势。看到用户意图比提出的解决方法更明显。尽管没有伤害,我只是分享我的想法。 =) – 2010-06-01 15:59:08

4

您尝试两次退出申请的决定。请尝试以下操作来代替:

private void xGameForm_FormClosing(object sender, FormClosingEventArgs e) { 
    if (DialogResult.No == MessageBox.Show("Are you sure you want to exit?", "Exit", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2)) 
     e.Cancel = true; 
} 

private void button1_Clink(object sender, EventArgs e) { 
    Close(); 
} 
+0

现货,正是我要说的。 MS很高兴为您取消应用程序退出(或任何Form.Close),但您必须这样做! – AAT 2010-06-01 15:58:02

相关问题