MessageBox on Form Closing
Asked Answered
M

1

9

I'm use this code for question before closing the application, but it is not working correctly.
My code is as below.

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
   DialogResult dlgresult = MessageBox.Show("Exit or no?",
                               "My First Application",
                               MessageBoxButtons.YesNo,
                               MessageBoxIcon.Information);
   if (dlgresult == DialogResult.No)
   {
      e.Cancel = true;

   }
   else
   {
     Application.Exit();
   }
}
Mockheroic answered 14/9, 2012 at 2:52 Comment(1)
after responding no it request again the question and closes equallyMockheroic
B
19

You don't need to explicitly call Application.Exit() since you are in the FormClosing event which means the Closing request has been triggered(e.g. click on the cross at the form button, this.Close()). You just need to intercept the closing request and indicate e.Cancel = true;

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    if(MessageBox.Show("Exit or no?",
                       "My First Application",
                        MessageBoxButtons.YesNo,
                        MessageBoxIcon.Information) == DialogResult.No) {
        e.Cancel = true;
    }
}
Besotted answered 14/9, 2012 at 3:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.