Home > Mobile >  The keydown function isn’t working for me
The keydown function isn’t working for me

Time:02-11

I have KeyPreview on true. Also, I tried making keydown print something with console.writeline and adding a breaking point, but it didn’t even run that. So basically, the function just isn’t running at all. Also, keyup isn’t working either.

 Private Sub Form1_KeyUp(sender As Object, Input As KeyEventArgs) Handles MyBase.KeyUp
    If Input.KeyCode = Keys.Up Then
        FedexMobile.Speed.Y = 0
    ElseIf Input.KeyCode = Keys.Down Then
        FedexMobile.Speed.Y = 0
    ElseIf Input.KeyCode = Keys.Left Then
        FedexMobile.Speed.X = 0
    ElseIf Input.KeyCode = Keys.Right Then
        FedexMobile.Speed.X = 0
    ElseIf Input.KeyCode = Keys.E Then

    End If
End Sub

Private Sub Form1_KeyDown(sender As Object, Input As KeyEventArgs) Handles MyBase.KeyDown
    If Input.KeyCode = Keys.Up Then
        FedexMobile.Speed.Y = Speed * -1
    ElseIf Input.KeyCode = Keys.Down Then
        FedexMobile.Speed.Y = Speed
    ElseIf Input.KeyCode = Keys.Left Then
        FedexMobile.Speed.X = Speed * -1
    ElseIf Input.KeyCode = Keys.Right Then
        FedexMobile.Speed.X = Speed
    ElseIf Input.KeyCode = Keys.O Then
        If Speed > 0 Then
            Speed = Speed - 1
        End If
    ElseIf Input.KeyCode = Keys.P Then
        If Speed < 10 Then
            Speed = Speed   1
        End If
    ElseIf Input.KeyCode = Keys.E Then

    End If

End Sub

CodePudding user response:

Check what control is currently focused. The Keys.Up, .Down, .Left and .Right KeyDown-Events only fire when there is no currently focused interaction-control, doesn't matter if KeyPreview is true or false. I don't know a "real" solution for this problem, but you can avoid it by adding a Label without text to your form and setting the TabIndex of this Label to 0.

CodePudding user response:

Well... If you cant get it to work, then you should be able to override the ProcessCmdKey and It should capture all the keys pressed by the user. I do not necessarily recommend this, however it will fire when any key is pressed. What you currently have technically "should" work as it did in my tests.

Protected Overrides Function ProcessCmdKey(ByRef msg As Message, ByVal keyData As Keys) As Boolean
  Debug.WriteLine("KeyData is: " & keyData.ToString())
  Return MyBase.ProcessCmdKey(msg, keyData)
End Function
  • Related