禁用 Alt+F4 但允许通过代码关闭表单,CloseReason.UserClosing 没有帮助
-
27-09-2019 - |
题
我希望表格不会通过执行而关闭 替代 + F4 但如果 Application.Exit()
或者 this.Close
从同一个表单调用,它应该被关闭。
我试过 CloseReason.UserClosing
但仍然没有帮助。
解决方案
如果你需要过滤掉 替代 + F4 仅事件(留下关闭框的点击, this.Close()
和 Application.Exit()
表现得像往常一样)那么我可以建议以下:
- 设置表格的
KeyPreview
财产给true
; 连接表格
FormClosing
和KeyDown
事件: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; }
其他提示
这是很容易的,你可以通过设置做到这一点的 SuppressKeyPress 属性为true的 Form_Keydown 事件处理程序如下。
if (e.KeyCode == Keys.F4 && e.Alt)
{
e.SuppressKeyPress = true;
}
有了这个,你还可以关闭你的活性形式由一套SuppressKeyPress属性对同一eventHandller或任何其他方式错误。
捕获ALT + F4热键通过窗体的KeyPreview属性设置为true,并覆盖OnProcessCmdKey方法。
你是如何使用CloseReason?
这里请参见示例代码: http://msdn.microsoft.com/ EN-US /库/ system.windows.forms.form.formclosing.aspx
您需要设置取消传递FormClosingEventArgs的属性对象以停止形式闭合。
不隶属于 StackOverflow