简体   繁体   中英

MessageBox on Form Closing

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

You don't need to explicitly call Application.Exit() since you are in the FormClosing event which means the Closing request has been triggered(eg 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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM