2

我试图在关闭菜单表单时关闭我的应用程序。这是我的代码:

private void frmMenu_FormClosing(object sender, FormClosingEventArgs e)
{
    var result = MessageBox.Show("Do you want to close this application",
        "Alert", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
    if (result == DialogResult.Yes)
    {
        //this.Close();
        Application.Exit();
        //e.Cancel = false;
    }
    else
    {
        e.Cancel = true;
    }
}

关闭时此消息出现两次。

4

4 回答 4

4

您不必再次退出,只需让它通过:

private void frmMenu_FormClosing(object sender, FormClosingEventArgs e)
{
    var result = MessageBox.Show("Do you want to close this application?",
        "Alert", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
    if (result == DialogResult.No)
    {
        e.Cancel = true;
    }
}
于 2012-10-31T10:47:37.823 回答
2

您可以覆盖该OnFormClosing方法:

protected override void OnFormClosing(FormClosingEventArgs e) {
        base.OnFormClosing(e);
        if (!e.Cancel) {
            if (MessageBox.Show("Do you want to close this application?", "Close Application", MessageBoxButtons.YesNo) != DialogResult.Yes) {
                e.Cancel = true;
            }
        }
    }

或者按照Hans Passant在课堂上使用 bool (例如IsDataValid)的评论中的建议:

private void frmMenu_FormClosing(object sender, FormClosingEventArgs e)
{ 
   if (!IsDataValid)
   {
       if(DialogResult.Yes == MessageBox.Show(Do you want to close this application?",
        "Alert", MessageBoxButtons.YesNo, MessageBoxIcon.Question))
           this.Dispose(); //or Application.Exit();
       else
            e.Cancel = true;
   }
   else
       this.Dispose(); //or Application.Exit();
}
于 2012-10-31T11:09:33.753 回答
1

您收到两条消息,因为Application.Exit();正在关闭frmMenu,而您当前正在关闭它 =>frmMenu已关闭两次。

IffrmMenu是您应用程序的主要形式,这意味着您的Program.cs文件中应该有类似的内容:

static class Program {
    [STAThread]
    static void Main() {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new FrmMenu());
    }
}

...然后应用程序将在关闭时退出frmMenu。正如derape所说,你不必打电话Application.Exit()

于 2012-10-31T10:57:29.640 回答
0
    private void frmMenu_FormClosing(object sender, FormClosingEventArgs e)
    {
        if (MessageBox.Show("Do you want to close this application", "Alert", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.No)
        {
            e.Cancel = true;
        }

    }
于 2014-06-27T11:18:42.083 回答