Home > Enterprise >  I am trying to use the KeyDown Event but nothing happens
I am trying to use the KeyDown Event but nothing happens

Time:04-03

If anyone can help me figure out what is wrong with this, my goal is to press F1/F2 and let the button be pressed without clicking on it, the form is always on top so it should work, even when i click on the form and do it within the form is does not work.

Private Sub saveBtn_KeyDown(sender As Object, e As KeyEventArgs) Handles saveBtn.KeyDown
        Select Case e.KeyCode
            Case Keys.F1
                saveBtn.PerformClick()
        End Select
    End Sub
    
    Private Sub save2_KeyDown(sender As Object, e As KeyEventArgs) Handles save2.KeyDown
        Select Case e.KeyCode
            Case Keys.F2
                save2.PerformClick()
        End Select
    End Sub

CodePudding user response:

You can also trap F1/F2 by overriding ProcessCmdKey() for the Form.

Just add this to the forms code:

Protected Overrides Function ProcessCmdKey(ByRef msg As Message, keyData As Keys) As Boolean
    Select Case keyData
        Case Keys.F1
            saveBtn.PerformClick()

        Case Keys.F2
            save2.PerformClick()

    End Select
    Return MyBase.ProcessCmdKey(msg, keyData)
End Function

CodePudding user response:

it will not work because you assigned the event to the button it will only work if the button is focused like selecting it with the tab key

what you should do is assign your code with the Window_PreviewKeyDown event

In the designer, set the KeyPreview property of your form to True. Then handle the form_KeyDown event, and check there if the F1/2 key was pressed.. The KeyPreview property of your form triggers the key events first on the form, and then on any control it was actually pressed

your code should be somthing like this

' look at the part of  Handles Me.PreviewKeyDown
Private Sub MainWindow_PreviewKeyDown(ByVal sender As Object, ByVal e As System.Windows.Input.KeyEventArgs) Handles Me.PreviewKeyDown
    Select Case e.Key
        Case Key.F1
            Me.Title = "F1 Key Down"
             saveBtn.PerformClick()
        ' Button1_Click(Nothing, Nothing)
        Case Key.F2
            save2.PerformClick()
        Case Key.S
            Me.Title = "S Key Down"
            e.Handled = True ' if your courser on a text box this will prevent it from getting the S keystroke
        Case Else
            Me.Title = "Another Key Down"
    End Select
End Sub
  • Related