10

我正在尝试让用户被提示确认退出我在 c# 中的程序,但由于某种原因,如果他们说“是”他们想退出,确认框会再次弹出。我不知道为什么。

    if (MessageBox.Show("Are you sure you want to exit?", "Confirm exit", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
    {
        e.Cancel = true;
    }
    else { Application.Exit(); }
4

4 回答 4

12

用这个

 private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
    {
        if (MessageBox.Show("Are you sure you want to close?", "Infomate", MessageBoxButtons.YesNo) == DialogResult.No)
        {
            e.Cancel = true;
        }        
    }
于 2012-01-11T10:41:56.117 回答
6

啊,你检查CloseReasonFormClosing活动吗?我认为你可能会因为两个不同的原因得到相同的事件(尽管我并不完全期望这会正常发生);检查你FormClosingEventArgs的参数是什么。

于 2011-01-07T02:45:09.713 回答
6

啊,我想出了如何解决它。我删除了 Application.Exit(); FormClosing 事件中的事件,并将其移至 FormClosed 事件中。现在一切正常。

于 2011-01-07T02:52:40.023 回答
1

作为SFD,他说您需要使用消息框创建事件。如果用户关闭表单和警告消息框,我添加了过滤器:

    private void close_confirmation(object sender, FormClosingEventArgs e)
    {
        if (e.CloseReason == CloseReason.FormOwnerClosing)
        {
            if (MessageBox.Show("Are you sure you want to close?", "Application", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.No)
            {
                e.Cancel = true;
            }
        }
    }

您需要将事件分配给表单以使其工作:

this.FormClosing += new FormClosingEventHandler(close_confirmation);

如果您想让它停止,以便用户可以再次关闭窗口而不显示消息:

this.FormClosing -= close_confirmation;
于 2021-01-06T15:37:15.303 回答