tags:

views:

51

answers:

2

How can I stop the message box from showing up twice when I press the X on the form ? FYI the butoon click works fine it's the X that prompts me twice.

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

At the point you make the Application.Exit call the form is still open (the closing event hasn't even finished processing). The Exit call causes the forms to be closed. Since the form is not yet closed it once again goes through the Closing path and hits your event handler.

One way to work around this is to remember the decision in an instance variable

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();
   }
JaredPar
thanks it works great
Michael Quiles
Wouldn't it be simpler just to cancel the exit if the user actually clicks no? Otherwise, the user confirms that he wishes to exit, then there is nothing more to do, as I can see it, as the application it already closing. Plus, there's a readbility advantage. It is more obvious to see the user intention, than the workaround proposed. No harm meant though, I only share my thought. =)
Will Marcouiller
+3  A: 

You try to exit the application twice. Try the following instead:

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();
}
Will Marcouiller
Spot on, just what I was going to say. MS are happy for you to cancel an application exit (or any Form.Close) but you have to do it there way!
AAT