Double confirmation on exit

Sean picture Sean · Jan 7, 2011 · Viewed 14.6k times · Source

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

Answer

SFD picture SFD · Jan 11, 2012

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