Visual Basic Key Listener - 按下2个键时给出响应

时间:2011-09-04 02:44:19

标签: vb.net keylistener

按照我之前提出的问题

Visual Basic Key Listener

我想知道如何编写代码,以便程序在同时按下2个箭头键时响应。换句话说,我希望程序能够像赛车游戏一样。

1 个答案:

答案 0 :(得分:1)

为了确定是否同时按下两个键,您需要存储已按下的键列表,在未按下时从列表中删除键。然后,您可以比较列表中的内容以设置模式,以查看它是否与您要查找的模式匹配。

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