单击"X"按钮时要求确认

10 c# button winforms

问题是消息框"肯定你想关闭?" 弹出,但当我点击"否"时,它仍然继续关闭程序.有什么建议?这是我的代码:

    protected override void OnFormClosing(FormClosingEventArgs e)
    {
        CloseCancel();
    }

    public static void CloseCancel()
    {
        const string message = "Are you sure that you would like to cancel the installer?";
        const string caption = "Cancel Installer";
        var result = MessageBox.Show(message, caption,
                                     MessageBoxButtons.YesNo,
                                     MessageBoxIcon.Question);

        if (result == DialogResult.Yes)
            Environment.Exit(0);
    }
Run Code Online (Sandbox Code Playgroud)

Ani*_*Ani 25

当您需要取消关闭操作时,您应该CancelFormClosingEventArgs参数的属性设置为true.而在明确Environment.Exit(0)通常不是必须的,因为形式是在它的途中被关闭任何方式(关闭进程的取消是一个可选项,而不是选择退出).

将最后一位替换为:

var result = MessageBox.Show(message, caption,
                             MessageBoxButtons.YesNo,
                             MessageBoxIcon.Question);

e.Cancel = (result == DialogResult.No);
Run Code Online (Sandbox Code Playgroud)


Unh*_*ean 6

e.Cancel在FormClosing事件上将停止关闭过程

    protected override void OnFormClosing(FormClosingEventArgs e)
    {
        if (CloseCancel()==false)
        {
            e.Cancel = true;
        };
    }

    public static bool CloseCancel()
    {
        const string message = "Are you sure that you would like to cancel the installer?";
        const string caption = "Cancel Installer";
        var result = MessageBox.Show(message, caption,
                                     MessageBoxButtons.YesNo,
                                     MessageBoxIcon.Question);

        if (result == DialogResult.Yes)
            return true;
        else
            return false;
    }
Run Code Online (Sandbox Code Playgroud)


Wic*_*cio 5

这个问题现在很老了,但这种方式更简单和简短,我认为它对到达此页面的人有用:

protected override void OnFormClosing(FormClosingEventArgs e)
{
    if (MessageBox.Show("Are you sure that you would like to cancel the installer?", "Cancel Installer", MessageBoxButtons.YesNo) == DialogResult.No)
    {
        e.Cancel = true;
    }
}
Run Code Online (Sandbox Code Playgroud)

并在别处使用this.Close()而不是函数。