Search code examples
vb.netkeypresskeydown

Using different KeyDown events in different objects but in the same form in vb.net


I have 2 buttons in one form called "button1" and "button2" I have the following code for both of my buttons :

   Private Sub Button2_KeyDown(sender As Object, e As KeyEventArgs) Handles Button2.KeyDown
    Select Case e.KeyData
        Case (Keys.F5)
            MsgBox("F5 in button 2")
        Case (Keys.F6)
            MsgBox("F6 in button 2")
        
    End Select


End Sub


Private Sub Button1_KeyDown(sender As Object, e As KeyEventArgs) Handles Button1.KeyDown
    If e.KeyCode.Equals(Keys.F9) Then
        MsgBox("F9 in button 1")
    End If
End Sub

With this code i'm trying activate two different buttons with different keys from the keyboard in the same form. The problem is that when I try to push the different keys of the different objects only one of them is registering the event.

Example: By deafult I think button 2 is activated so everytime i press f5 and f6 the proper message display with no problem but when press the f9 key is not actually triggering the other event of button 1. I have to click the buttons separately to activate them and then the events register properly .

it's possible to have both of them activated at the same time ?


Solution

  • You have written 2 different KeyDown events, so if the active control is button2, F5 and F6 will work. if the active control is button1, F9 will.

    set the KeyPreview property of the form to true and create another KeyDown event for the form like this:

    Private Sub Form1_KeyDown(sender As Object, e As KeyEventArgs) Handles Form1.KeyDown
        If e.KeyCode.Equals(Keys.F9) Then
            Button1_KeyDown(Me, e)
        End If
       Select Case e.KeyData
            Case (Keys.F5)
               Button2_KeyDown(Me, e)
            Case (Keys.F6)
               Button2_KeyDown(Me, e)
            
        End Select
    End Sub
    

    Having KeyPreview = True the KeyDown will only work for form and not for the buttons, and from there you can call your desired event.