0

按下两个方向键时如何沿对角线移动对象?怎么做?我尝试将 elseif 语句添加到一起处理向上和向右,但是当我将它们按在一起时它仍然向上或向右移动

  Private Sub Form1_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles MyBase.KeyDown
    If e.KeyCode = Keys.Right Then
        Label1.Location = New Point(Label1.Location.X + 5, Label1.Location.Y)

    ElseIf e.KeyCode = Keys.Left Then
        Label1.Location = New Point(Label1.Location.X - 5, Label1.Location.Y)

    ElseIf e.KeyCode = Keys.Down Then
        Label1.Location = New Point(Label1.Location.X, Label1.Location.Y + 5)

    ElseIf e.KeyCode = Keys.Up Then
        Label1.Location = New Point(Label1.Location.X, Label1.Location.Y - 5)

    ElseIf e.KeyCode = Keys.Up And e.KeyCode = Keys.Right Then
        Label1.Location = New Point(Label1.Location.X + 5, Label1.Location.Y + 5)
    End If

    CheckIntersections()
    If Label1.Location.Y < 0 Then
        Label1.Location = New Point(Label1.Location.X, Me.Height)
    ElseIf Label1.Location.Y > Me.Height Then
        Label1.Location = New Point(Label1.Location.X, Me.Bottom = 0)
    ElseIf Label1.Location.X < 0 Then
        Label1.Location = New Point(Me.Width, Label1.Location.Y)
    ElseIf Label1.Location.X > Me.Width Then
        Label1.Location = New Point(0, Label1.Location.Y)
    End If
End Sub
4

1 回答 1

1

KeyDown每次按下单个键时都会发生该事件。因此,您需要记住当光标键被按下一次时,KeyDown以检查另一个光标键被按下的情况。

请记住订阅KeyUp事件以清除状态,因为用户可以按下一个光标键,释放它,然后再按下另一个。

您的代码将永远无法工作:

ElseIf e.KeyCode = Keys.Up And e.KeyCode = Keys.Right Then

因为这不可能是真的。KeyCode是单键码,不能既是一键又是另一键。

于 2013-03-09T09:07:06.707 回答