【问题标题】:Disable Alt+F4 but allow the form to be closed by code, CloseReason.UserClosing is not helping禁用 Alt+F4 但允许通过代码关闭表单,CloseReason.UserClosing 无济于事
【发布时间】:2010-04-15 08:22:08
【问题描述】:

我希望表单不会通过执行 Alt + F4 来关闭,但是如果从同一个表单调用 Application.Exit()this.Close,它应该被关闭.

我尝试了CloseReason.UserClosing,但仍然没有帮助。

【问题讨论】:

  • 您需要只过滤掉 Alt+F4 还是点击关闭按钮?

标签: c# .net winforms application-close


【解决方案1】:

如果您只需要过滤掉 Alt + F4 事件(让点击关闭框、this.Close()Application.Exit() 正常运行),那么我可以建议如下:

  1. 设置表单的KeyPreview 属性给true
  2. 连接表单的FormClosingKeyDown 事件:

    private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
        if (_altF4Pressed)
        {
            if (e.CloseReason == CloseReason.UserClosing)
                e.Cancel = true;
            _altF4Pressed = false;
        }
    }
    
    private bool _altF4Pressed;
    private void Form1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.Alt && e.KeyCode == Keys.F4)
            _altF4Pressed = true;
    }
    

【讨论】:

  • 太好了,非常感谢。这一行非常重要:if (e.Alt && e.KeyCode == Keys.F4)
  • 这一行也很重要!将表单的 KeyPreview 属性设置为 true;
【解决方案2】:

您可以通过在 Form_Keydown EventHandler 上将 SuppressKeyPress 属性设置为 true 来实现这一点,如下所示。

        if (e.KeyCode == Keys.F4 && e.Alt)
        {
            e.SuppressKeyPress = true;

        }

您还可以通过在同一 eventHandller 或任何其他方式上将 SuppressKeyPress 属性设置为 false 来关闭您的活动表单。

【讨论】:

    【解决方案3】:

    通过将 Form 的 KeyPreview 属性设置为 true 并覆盖 OnProcessCmdKey 方法来捕获 Alt+F4 热键。

    【讨论】:

      【解决方案4】:

      您是如何使用 CloseReason 的?

      在此处查看示例代码: http://msdn.microsoft.com/en-us/library/system.windows.forms.form.formclosing.aspx

      您需要设置传递的 FormClosingEventArgs 对象的 Cancel 属性来停止表单关闭。

      【讨论】:

      • FormClosing 事件的问题在于 Alt+F4 和调用this.Close() 将无法区分——它们都将具有CloseReason.UserClosing
      • 在调用 this.Close() 之前设置一个可以在 FormClosing 中检查的属性...
      • 这将起作用,您实际上可以控制在哪里调用表单的Close 方法。如果它可以在某个时刻被某些第三方组件调用怎么办?.. 此外,CloseReason.UserClosing 将在单击表单的关闭框时设置。 (这是期望的行为?)
      猜你喜欢
      • 2010-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-09
      • 1970-01-01
      • 1970-01-01
      • 2018-10-31
      • 1970-01-01
      相关资源
      最近更新 更多