【问题标题】:Close form program when close button is disabled [duplicate]禁用关闭按钮时关闭表单程序[重复]
【发布时间】:2016-01-06 17:25:04
【问题描述】:

我想在按下按钮时关闭应用程序,但我想禁用关闭按钮(X 按钮右上角)。

我用这段代码禁用了关闭按钮:

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

但现在当我尝试使用此代码关闭程序时,它不会工作。

private void button1_Click(object sender, EventArgs e)
{
    Application.Exit();
}

有没有办法在点击按钮时关闭这个程序?

【问题讨论】:

  • 这是一种相当残酷的用户体验。不要禁用关闭按钮;如果他们想关闭程序,让他们使用它。

标签: c# .net winforms


【解决方案1】:

在事件处理程序中,检查CloseReason property of the FormClosingEventArgs:

这允许您根据 how the close was initiated 采取不同的行为,因此在应用程序退出(或 Windows 关闭)的情况下,您可以允许表单关闭。

protected override void OnFormClosing(FormClosingEventArgs e)
{
    if (e.CloseReason != CloseReason.ApplicationExitCall
     && e.CloseReason != CloseReason.WindowsShutDown)
     {
          e.Cancel = true;
     }
}

【讨论】:

    【解决方案2】:

    您总是取消表单的 closign,这就是它不起作用的原因。

    试试这个:

    bool blockClosing = true;
    
    protected override void OnFormClosing(FormClosingEventArgs e)
    {
        e.Cancel = blockClosing;
    }
    
    private void button1_Click(object sender, EventArgs e)
    {
        blockClosing = false;
        Application.Exit();
    }
    

    这样,当你按下你的按钮时,它就会关闭 tha pp。

    【讨论】:

      【解决方案3】:

      FormClosingEventArgs 有一个Reason 成员,它告诉你究竟是什么试图关闭你的表单。只需允许ApplicationExitCall 通过而不取消它。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-03-23
        • 1970-01-01
        • 1970-01-01
        • 2014-10-08
        • 2013-04-14
        • 2011-01-22
        • 1970-01-01
        • 2011-09-04
        相关资源
        最近更新 更多