MessageBox on Form Closing

让人想犯罪 __ 提交于 2019-12-04 01:17:34

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/12417504/messagebox-on-form-closing

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!