10

I am trying to make it so that the user is prompted to confirm exiting my program in c#, but for some reason, if they say "yes" they would like to exit, the confirmation box would pop up again. I can't figure out why.

    if (MessageBox.Show("Are you sure you want to exit?", "Confirm exit", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
    {
        e.Cancel = true;
    }
    else { Application.Exit(); }
6
  • 1
    Where is this code being run? Commented Jan 7, 2011 at 2:38
  • 1
    I am assuming you are handling Form Close event. I don't think you need Application.Exit() Commented Jan 7, 2011 at 2:39
  • Yes, form closing, but I do need application.exit() as there is another window open that I need to close at the same time.
    – Sean
    Commented Jan 7, 2011 at 2:41
  • In your Application.Run(), which form are you passing in? Commented Jan 7, 2011 at 2:42
  • StartupWindow(), and the window that is closing is BackupWindow(). I need both of them to close if one of them closes, so I found the easiest way to do that is to simply use Application.Exit().
    – Sean
    Commented Jan 7, 2011 at 2:45

4 Answers 4

12

Use this

 private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
    {
        if (MessageBox.Show("Are you sure you want to close?", "Infomate", MessageBoxButtons.YesNo) == DialogResult.No)
        {
            e.Cancel = true;
        }        
    }
6

Ah, did you check the CloseReason for the FormClosing event? I think you might get the same event for two different reasons (although I don't exactly expect that to happen normally); check your FormClosingEventArgs to see what the parameters are.

6

Ah, I figured out how to fix it. I removed the Application.Exit(); event from the FormClosing event, and moved it into the FormClosed event. It all works now.

1
  • I got the same weird issue as you and your answer solved it perfeclty.
    – 8oris
    Commented Feb 18, 2022 at 10:05
1

As SFD he said you need to create the event with the message box. I've added to filter if the user it's closing the form and a warning messagebox:

    private void close_confirmation(object sender, FormClosingEventArgs e)
    {
        if (e.CloseReason == CloseReason.FormOwnerClosing)
        {
            if (MessageBox.Show("Are you sure you want to close?", "Application", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.No)
            {
                e.Cancel = true;
            }
        }
    }

You nee to assign the event to the form to make it work:

this.FormClosing += new FormClosingEventHandler(close_confirmation);

If you want to make it stop so the user can close again the window without the message:

this.FormClosing -= close_confirmation;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.