Reputation: 15813
I would like to set the focus onto a control when the user presses Alt+D. However, Alt+D sets the focus on the first item in the menustrip after setting the focus in the keydown event handler.
Setting the form KeyPreview to True and e.Handled to true when the Alt key is pressed has no effect.
D is an arbitrary key for this example -- it happens on all alpha keys.
I'm using vb.net 2008.
Sample code:
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
Sample form, after pressing Alt+D. Focus was on Button2 before pressing Alt+D.
Upvotes: 1
Views: 237
Reputation: 156958
You should override the ProcessDialogKey
method.
This code will do:
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
Upvotes: 2
Reputation: 1393
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
Upvotes: 2