【问题标题】:C# - Override the Standard Windows Close Button to Pop-up my Custom FormC# - 覆盖标准 Windows 关闭按钮以弹出我的自定义表单
【发布时间】:2014-06-27 12:10:26
【问题描述】:

是的,菜鸟问题。我很抱歉。

当用户单击窗口上的红色 x 按钮时,我想弹出一条消息,询问他们是否真的要退出。我在这个网站上发现了一个类似的问题:Override standard close (X) button in a Windows Form

问题是,我想为 MessageBox 自定义字体和 MessageBoxIcon,遗憾的是它无法完成(或者需要付出很多努力才能完成)。所以,我决定制作自己的表格。

    protected override void OnFormClosing(FormClosingEventArgs e)
    {
        if (txtID.Text != "" || txtPassword.Text != "")
        {
            base.OnFormClosing(e);
            if (e.CloseReason == CloseReason.WindowsShutDown) return;

            // Confirm user wants to close
            new formConfirmExit().ShowDialog();
        }
    }

我在主窗体下添加了这段代码。但是,当我运行我的代码并单击标准关闭按钮时,我的弹出窗口(我所做的自定义表单)并没有完成它的工作。假设我单击“否”按钮,它会终止我的整个程序。使用“是”按钮,弹出窗口再次出现,然后一切都停止了(在 Visual Studio 上)和 ta-da!一个例外。

顺便说一句,这些是“是”和“否”按钮方法(来自我的自定义表单类):

    private void btnYes_Click(object sender, EventArgs e)
    {
        Application.Exit(); // terminate program (exception is in here)
    }

    private void btnNo_Click(object sender, EventArgs e)
    {
        this.Close(); // close this pop up window and go back to main window
    }

Application.Exit() 更改为Environment.Exit(0) 完成了“是”按钮的工作,但我的“否”按钮仍然会终止程序。

编辑:当我单击“是”按钮时,弹出窗口/我的自定义表单再次显示(仅一次)。它将保持该状态(我可以反复单击“是”按钮但没有任何反应)。当我先单击是按钮(注意本段的第一句)然后单击否按钮时,将引发 InvalidOperationException。

谢谢。

【问题讨论】:

  • 试试 this.Hide() 而不是 this.Close()
  • InvalidOperationException.
  • 消息框表单中的用户 DialogResult,在每个按钮单击并关闭该表单时为 in 分配适当的值。之后检查主窗体中的 DialogResult 值
  • @Imapler:我试过了。好像没修:(
  • @user2767299:感谢您的想法。我想我在这里接受的答案适用。

标签: c# forms overriding


【解决方案1】:

将此添加到您的 No_Click 中:

private void btnNo_Click(object sender, EventArgs e)
{
    DialogResult = DialogResult.No;
}

然后,将您的表单关闭事件更改为以下内容:

protected override void OnFormClosing(FormClosingEventArgs e)
{
    if (txtID.Text != "" || txtPassword.Text != "")
    {
        base.OnFormClosing(e);
        if (e.CloseReason == CloseReason.WindowsShutDown
            || e.CloseReason == CloseReason.ApplicationExitCall)
                return;

        // Confirm user wants to close
        using(var closeForm = new formConfirmExit())
        {
            var result = closeForm.ShowDialog();
            if (result == DialogResult.No)
                e.Cancel = true;   
        }
    }       
}

首先,它会检查表单是否没有通过Application.Exit() 关闭,这可能是由您的其他表单触发的,因此它不会重新显示自定义消息框。

其次,围绕自定义表单创建 using 语句。这样您就可以保留这些值。然后,如果用户不想取消,则将 dialogresult 设置为no。如果是这种情况,请将e.Cancel = true 设置为停止退出。

【讨论】:

    猜你喜欢
    • 2010-12-12
    • 1970-01-01
    • 2013-05-17
    • 1970-01-01
    • 2014-01-19
    • 1970-01-01
    • 2012-03-21
    • 1970-01-01
    • 2012-12-17
    相关资源
    最近更新 更多