vb.net - keydown / up问题

时间:2011-04-06 21:27:16

标签: vb.net

我可以使用此代码检测单个键,但是一旦我按下多个键,vb.net就会忽略以前的键而只关注另一个键。有人可以帮我弄清楚如何同时检测多个keydowns吗?

Private Sub frmMain_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
    If e.KeyCode = Keys.W Or e.KeyCode = Keys.S Or e.KeyCode = Keys.A Or e.KeyCode = Keys.D Then
        lblDrive.Text = "Driving:     "
        If e.KeyCode = Keys.W Then
            lblDrive.Text = lblDrive.Text & "FORWARD  "
        End If
        If e.KeyCode = Keys.S Then
            lblDrive.Text = lblDrive.Text & "REVERSE  "
        End If
        If e.KeyCode = Keys.A Then
            lblDrive.Text = lblDrive.Text & "LEFT  "
        End If
        If e.KeyCode = Keys.D Then
            lblDrive.Text = lblDrive.Text & "RIGHT  "
        End If

    End If
End Sub

3 个答案:

答案 0 :(得分:1)

您是否可以保留已关闭的密钥列表,并将其从KeyUp上的此列表中删除?

KeyDown事件仅告知您新密钥何时关闭。对于同时按下的键,您也不会获得KeyDown消息...因为这些键实际上从未被同时按下。

因此,在KeyDown上,将密钥添加到列表/数组/中,然后在KeyUp上将其从该列表中删除。

答案 1 :(得分:0)

问题是除了Control,Shift和Alt之类的修改键之外,两个键永远不会同时发生故障。操作系统将始终选择胜利者,而下行事件将按顺序交付。

答案 2 :(得分:0)

试试我写的这个课:

Public Class Keyboard
    Inherits Dictionary(Of Keys, Boolean)

    Public Sub New()
        For Each key As System.Windows.Forms.Keys In [Enum].GetValues(GetType(System.Windows.Forms.Keys))
            If Not Me.ContainsKey(key) Then Me.Add(key, False)
        Next
    End Sub

    Private Sub KeyDown_Listener(ByVal sender As Object, ByVal e As KeyEventArgs)
        Me(e.KeyCode) = True
    End Sub
    Private Sub KeyUp_Listener(ByVal sender As Object, ByVal e As KeyEventArgs)
        Me(e.KeyCode) = False
    End Sub
    Private Sub LostFocus_Listener(ByVal sender As Object, ByVal e As EventArgs)
        For i As Integer = 0 To Me.Keys.Count - 1
            Me(Me.Keys(i)) = False
        Next
    End Sub

    Public Sub Attach(ByVal Control As Control)
        AddHandler Control.KeyDown, AddressOf KeyDown_Listener
        AddHandler Control.KeyUp, AddressOf KeyUp_Listener
        AddHandler Control.LostFocus, AddressOf LostFocus_Listener
    End Sub

    Public Function GetPressedKeys() As List(Of Keys)
        Return (From e As KeyValuePair(Of Keys, Boolean) In Me Where e.Value = True Select e.Key).ToList
    End Function
    Public Function GetUnPressedKeys() As List(Of Keys)
        Return (From e As KeyValuePair(Of Keys, Boolean) In Me Where e.Value = False Select e.Key).ToList
    End Function

    Public Function IsKeyPressed(ByVal Key As Keys) As Boolean
        Return Me(Key)
    End Function

End Class

将其设为表单类的成员并在其中抛出Keyboard.Attach(Me)