Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Double confirmation on exit

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(); }
like image 815
Sean Avatar asked Jan 07 '11 02:01

Sean


4 Answers

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.

like image 64
Sean Avatar answered Nov 15 '22 06:11

Sean


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;
like image 22
Alexandru-Codrin Panaite Avatar answered Nov 15 '22 05:11

Alexandru-Codrin Panaite


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;
        }        
    }
like image 12
SFD Avatar answered Nov 15 '22 04:11

SFD


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.

like image 6
user541686 Avatar answered Nov 15 '22 04:11

user541686