简体   繁体   中英

Why does Application.Exit Prompt me twice?

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

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

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

这将起作用: Application .ExitThread();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM