Frage

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();
   }
}
War es hilfreich?

Lösung

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;
    }
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top