当我选择否时,表格仍然关闭

时间:2015-04-22 23:51:07

标签: c# winforms

我有以下代码

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    if (cmd.cetakTanya("Are you sure you want to exit ?"))
    {
        cmd.cetakSukses("Thank you for using " + cmd.title);
        startURL();
    }
}

public bool cetakTanya(string message)
{
    bool status = false;

    DialogResult dialogResult = MessageBox.Show(message, title, MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation);
    if (dialogResult == DialogResult.Yes)
    {
        status = true;
    }
    else if (dialogResult == DialogResult.No)
    {
        status = false;
    }
    return status;
}

为什么我的表单仍然关闭,即使我在确认对话框中选择“否”?

2 个答案:

答案 0 :(得分:4)

您需要取消活动:

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    if (cmd.cetakTanya("Are you sure you want to exit ?"))
    {
        cmd.cetakSukses("Thank you for using " + cmd.title);
        startURL();
    }
    else
    {
        e.Cancel = true;
    }
}

答案 1 :(得分:1)

如果" no"使用Cancel属性取消活动点击。

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    if (cmd.cetakTanya("Are you sure you want to exit ?"))
    {
        cmd.cetakSukses("Thank you for using " + cmd.title);
        startURL();
    }
    else
        e.Cancel = true;
}

此外,您的方法可以重构为更紧凑:

public bool cetakTanya(string message)
{
    var result = MessageBox.Show(message, title, MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation);
    return result == DialogResult.Yes;
}