【发布时间】:2010-04-15 08:22:08
【问题描述】:
我希望表单不会通过执行 Alt + F4 来关闭,但是如果从同一个表单调用 Application.Exit() 或 this.Close,它应该被关闭.
我尝试了CloseReason.UserClosing,但仍然没有帮助。
【问题讨论】:
-
您需要只过滤掉 Alt+F4 还是点击关闭按钮?
标签: c# .net winforms application-close
我希望表单不会通过执行 Alt + F4 来关闭,但是如果从同一个表单调用 Application.Exit() 或 this.Close,它应该被关闭.
我尝试了CloseReason.UserClosing,但仍然没有帮助。
【问题讨论】:
标签: c# .net winforms application-close
如果您只需要过滤掉 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;
}
【讨论】:
您可以通过在 Form_Keydown EventHandler 上将 SuppressKeyPress 属性设置为 true 来实现这一点,如下所示。
if (e.KeyCode == Keys.F4 && e.Alt)
{
e.SuppressKeyPress = true;
}
您还可以通过在同一 eventHandller 或任何其他方式上将 SuppressKeyPress 属性设置为 false 来关闭您的活动表单。
【讨论】:
通过将 Form 的 KeyPreview 属性设置为 true 并覆盖 OnProcessCmdKey 方法来捕获 Alt+F4 热键。
【讨论】:
您是如何使用 CloseReason 的?
在此处查看示例代码: http://msdn.microsoft.com/en-us/library/system.windows.forms.form.formclosing.aspx
您需要设置传递的 FormClosingEventArgs 对象的 Cancel 属性来停止表单关闭。
【讨论】:
FormClosing 事件的问题在于 Alt+F4 和调用this.Close() 将无法区分——它们都将具有CloseReason.UserClosing。
Close 方法。如果它可以在某个时刻被某些第三方组件调用怎么办?.. 此外,CloseReason.UserClosing 将在单击表单的关闭框时设置。 (这是期望的行为?)