Почему Application.Exit запрашивает меня дважды? - PullRequest
1 голос
/ 01 июня 2010

Как я могу остановить отображение окна сообщения дважды при нажатии 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();
   }

Ответы [ 2 ]

6 голосов
/ 01 июня 2010

В момент вызова 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();
   }
4 голосов
/ 01 июня 2010

Вы пытаетесь выйти из приложения дважды. Вместо этого попробуйте следующее:

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();
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...