为什么Application.Exit提示我两次?

时间:2010-06-01 15:49:28

标签: c# winforms

当我按下表单上的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();
   }

3 个答案:

答案 0 :(得分:6)

在您进行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();
   }

答案 1 :(得分: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();
}

答案 2 :(得分:-1)

这将起作用: 应用程序.ExitThread();