当控件具有焦点时如何用键盘关闭 WinForm
当其中存在一些控件(如树视图、按钮和其他内容)并且它们具有焦点并且可能具有相同的键盘快捷键时,我如何关闭我的 C# WinForms 程序?
例如,在我的树视图中,如果按 ALT + ESC 键,节点将被删除。但我希望能够通过按 ESC 键来调用“this.Close()”方法,无论是否有任何控件具有焦点。
谢谢。
How can I close my C# WinForms program while there are some controls like treeviews, buttons and other stuff are present in it and they have focous and that could be they have same keyboard shortcut?
forexample in my treeview if I press ALT + ESC key, the nodes will be removed. but I want to be able by pressing ESC key the 'this.Close()' method to be called no matter if any control has focus.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
将表单的
KeyPreview
属性设置为 true。这允许您在控件处理程序之前处理表单处理程序中的键盘消息,即使控件具有焦点也是如此。Set
KeyPreview
property of your form to true. This allows you to handle keyboard message in form handlers before control handlers even if control has focus.也许您可以通过覆盖
Form
来尝试此操作Maybe you could try this by overriding on the
Form
您需要将表单的
KeyPreview
属性设置为true
。这将使表单能够在按键传递到其上的控件之前捕获它们,这使您可以拦截它们并在需要时将它们传递,或者执行其他操作,例如使用组合键关闭表单。You need to set the form's
KeyPreview
property totrue
. This will enable the form to capture keypresses before they are passed on to the controls on it, which makes it possible for you to intercept them and pass them on if you want to, or do something else, like closing the form with your key combination.它已经内置于 Windows 中。 Alt-F4 将关闭前台应用程序。您不需要做任何特别的事情来自己处理这个问题。如果您只想关闭一个窗口,而不是整个应用程序(例如在 MDI 风格的界面中),那么 Ctrl-F4 就可以了。
It's already built into Windows. Alt-F4 will close the foreground application. You don't need to do anything special to handle this yourself. If you want to close just one window, and not the whole application, such as in a MDI-style interface, then Ctrl-F4 will do the trick.
将Form的
KeyPreview
属性设置为true(它将在控件之前将keyborad事件传递到窗体。),并在KeyXXX事件上编写代码,并检查ESC键并调用this .close()
Set the
KeyPreview
property of the Form to true(it will transfer the keyborad event to form before the controls.), and write code on the KeyXXX event, and check for ESC key and callthis.close()