c# - 禁用 Alt+F4 但允许通过代码关闭表单,CloseReason.UserClosing 没有帮助

标签 c# .net winforms application-close

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

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

最佳答案

如果您只需要过滤掉 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;
    }
    

关于c# - 禁用 Alt+F4 但允许通过代码关闭表单,CloseReason.UserClosing 没有帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2643712/

相关文章:

c# - 参数化 Function app 的 settings.json 以进行发布

.net - 正确的方法来使Winforms UI阻塞对话框,直到出现一些非用户驱动的事件条件?

c# - 如何设置 ASPNETCORE_ENVIRONMENT 以考虑发布 ASP.NET Core 应用程序

c# - 将 XML 反序列化为从基类 C# 派生的对象

c# - MAF 安全 : How to prevent a "Man-in-the-Middle" Attack

C#/MongoDB : How do I keep a connection alive?

c# - 如何防止生成验证属性?

c# - 如何使列完全填充数据 GridView

c# - 在移动鼠标并按住右键的同时画一条线

c# - 在 C# 中编码 C 结构