简体   繁体   中英

C# WINForm avoid two message box

I have a GUI program with one "Exit" button. When clicking this button, it would call the Application.Exit() to close this program. Before closing the program, it also calls a confirm message box. I also implement the Closing Event for this GUI main form. In this event, it also calls a confirm message box, then calls the Application.Exit().

Now, When I just close the GUI, it would popup a confirm message box, then close it, all is fine. When I click the "Exit" Button, it would popup the confirm message box twice. I think when it call the Application.Exit(), the Closing event is invoked.

Is there any method to avoid twice confirm message box?

Best Regards,

What you could do is remove the confirm button from the Application.Exit() method and keep it just in the Closing Event. Then instead of calling Application.Exit() directly in your button click event, instead call Form.Close() method of the form;

This should be all you need. Calling the Close method on your form will close the form, and if that is your only form running in the application, it will also end the application.

    private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
        if (MessageBox.Show("Really want to close?", "Closing"
            , MessageBoxButtons.YesNo) == DialogResult.No)
        {
            e.Cancel = true;
        }
    }

    private void btnExit_Click(object sender, EventArgs e)
    {
        this.Close();
    }

If the logic around your app does not cause the application to exit after the form is closed, you should just call Application.Exit in the Form_Closed event like this:

    private void Form1_FormClosed(object sender, FormClosedEventArgs e)
    {
        Application.Exit();
    }

you could use a global lock object for your messages.

whenever you feel like showing a message box you'd write something like this:

lock (mymessages)
{
  if (!nomoremessages)
  {
    MessageBox.Show("Hi");
    nomoremessages = true;
  }
}

This shall ensure only the first message will ever be shown.

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