开发者

Visual Basic Key Listener - give response when 2 keys are pressed

Following the question I have asked before at

Visual Basic Key Listener

I am wondering on how to write the code such that the program will respond when 2 arrow keys are pressed at the same time. In other words, I would like to have the program to behave l开发者_Go百科ike a racing game.


In order to find out if two keys are pressed at the same time, you'll need to store a list of keys that have been pressed, removing keys from the list when they are unpressed. You can then compare what's in the list to set patterns to see if it matches any of the ones that you are looking for.

Dim keysPressed as New HashSet(Of Keys)

Private Sub Form1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown

    'Add the pressed key into the list
    keysPressed.Add(e.KeyCode)

    If keysPressed.Contains(Keys.W) AndAlso keysPressed.Contains(Keys.A) Then
        'Add code to take action here
    End If

    If keysPressed.Contains(Keys.D) AndAlso keysPressed.Contains(Keys.A) Then
        'Add code to take action here
    End If

    'Add more code to handle actions for multiple keys being pressed
End Sub

Private Sub Form1_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyUp
    'Remove the pressed key from the list 
    keysPressed.Remove(e.KeyCode)
End Sub
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜