我希望表单不会通过执行 Alt + F4 关闭,但是如果 Application.Exit()
或 this。 Close
是从同一个表单调用的,它应该被关闭。
我尝试了 CloseReason.UserClosing
但仍然没有帮助。
最佳答案
如果您只需要过滤掉 Alt + 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; }
关于c# - 禁用 Alt+F4 但允许通过代码关闭表单,CloseReason.UserClosing 没有帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2643712/