整个表单上的 vb.net Keydown 事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13727172/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
vb.net Keydown event on whole form
提问by Malik
I have a form with several controls. I want to run a specific sub on keydown event regardless any controls event. I mean if user press Ctrl+S anywhere on form it execute a subroutine.
我有一个带有多个控件的表单。无论任何控件事件,我都想在 keydown 事件上运行特定的子程序。我的意思是,如果用户在表单上的任意位置按下 Ctrl+S,它就会执行一个子程序。
回答by Steve
You should set the KeyPreviewproperty on the form to True and handle the keydown event there
您应该将表单上的KeyPreview属性设置为 True 并在那里处理 keydown 事件
When this property is set to true, the form will receive all KeyPress, KeyDown, and KeyUp events. After the form's event handlers have completed processing the keystroke, the keystroke is then assigned to the control with focus. .......... To handle keyboard events only at the form level and not allow controls to receive keyboard events, set the KeyPressEventArgs.Handled property in your form's KeyPress event handler to true.
当此属性设置为 true 时,表单将接收所有 KeyPress、KeyDown 和 KeyUp 事件。在窗体的事件处理程序完成对击键的处理后,击键被分配给具有焦点的控件。..........要仅在窗体级别处理键盘事件并且不允许控件接收键盘事件,请将窗体的 KeyPress 事件处理程序中的 KeyPressEventArgs.Handled 属性设置为 true。
So, for example, to handle the Control+S key combination you could write this event handler for the form KeyDown event.
因此,例如,要处理 Control+S 组合键,您可以为表单 KeyDown 事件编写此事件处理程序。
Private Sub Form1_KeyDown(ByVal sender As Object, ByVal e As KeyEventArgs) Handles MyBase.KeyDown
If e.Control AndAlso e.KeyCode = Keys.S then
' Call your sub method here .....
YourSubToCall()
' then prevent the key to reach the current control
e.Handled = False
End If
End Sub
回答by Kratz
I've used this code in my forms before and it seems to work pretty good.
我以前在我的表单中使用过这段代码,它似乎工作得很好。
Protected Overrides Function ProcessKeyPreview(ByRef m As System.Windows.Forms.Message) As Boolean
If m.Msg = &H100 Then 'WM_KEYDOWN
Dim key As Keys = m.WParam
If key = Keys.S And My.Computer.Keyboard.CtrlKeyDown Then
'DO stuff
Return True
End If
End If
Return MyBase.ProcessKeyPreview(m)
End Function