当用户按 Alt + D 时,我想将焦点设置到控件上。但是,在keydown事件处理程序中设置焦点后, Alt + D 将焦点设置在menustrip中的第一个项目上。
当按下 Alt 键时,将表单KeyPreview设置为True并将e.Handled设置为true无效。
D是此示例的任意键 - 它出现在所有字母键上。
我正在使用vb.net 2008。
示例代码:
Private Sub Form1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
If e.Alt And e.KeyCode = Keys.D Then
Button1.Focus()
e.Handled = True
End If
End Sub
按 Alt + D 后的样本表单。在按 Alt + D 之前,焦点在Button2上。
答案 0 :(得分:2)
您应该覆盖ProcessDialogKey
方法。
此代码将执行:
Protected Overrides Function ProcessDialogKey(ByVal keyData As Keys) As Boolean
If keyData = (Keys.Alt Or Keys.D) Then
Call Form1_KeyDown(Nothing, New KeyEventArgs(Keys.Alt Or Keys.D))
Return True
Else
Return MyBase.ProcessDialogKey(keyData)
End If
End Function
答案 1 :(得分:2)
Protected Overrides Function ProcessCmdKey(ByRef msg As Message, ByVal keyData As Keys) As Boolean
If keyData = Keys.Alt And keyData = Keys.D Then
Button1.Focus()
End If
Return True 'im not sure about this, I forgot the code
Return MyBase.ProcessCmdKey(msg, keyData)
End Function