Oyente de claves de Visual Basic

I am trying to write a program in Visual Basic (with VS 2010) that will respond to the arrow keys. I am aware that there are key listener in Java but not sure if such thing exist in VB and how to code it. Please show me some example on this. Thanks.

preguntado el 27 de agosto de 11 a las 16:08

1 Respuestas

If you are doing winforms then set the KeyPreview property of the form to true and then set the KeyDown event. Your code will be like this:

Dim previousKey As Keys? = Nothing

Private Sub Form1_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles MyBase.KeyDown
    If e.KeyCode = Keys.Up Then
        'up arrow
    End If

    If e.KeyCode = Keys.Left Then
        'left arrow
        If Not previousKey Is Nothing And previousKey = Keys.Up Then
            'Up arrow and then Left Arrow
            MessageBox.Show("there, that's better")
        End If
    End If

    If e.KeyCode = Keys.Right Then
        'right arrow
    End If

    If e.KeyCode = Keys.Down Then
        'down arrow
    End If

    'After everything is done set the current key as the previous key.
    previousKey = e.KeyCode
End Sub

Respondido 29 ago 11, 15:08

Thanks a lot. That's what I want. - yihangho

Ok. Now, is it possible to have the program respond when 2 keys are pressed? Like when up arrow key and left arrow key are pressed? - yihangho

I have modified my example to capture Up arrow and then Left arrow. - Johnie Karr

Is it possible to make it behave like the way racing game behave? - yihangho

Well, racing games exist so I'd say it is possible. You need to create a new post though with the specific problem that you have and what you have tried in resolving it. - Johnie Karr

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.