2013-03-09 78 views
0

如何在两个方向键被按下时以对角线方式移动物体?怎么做? 我尝试添加ELSEIF语句处理向上和向右在一起,但它仍然向上或权当我一起按他们VB.NET使用键对角移动物体

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 

回答

1

KeyDown事件的每一个键被按下时有发生。因此,您需要记住一旦出现KeyDown时按下光标键以检查另一次事件是否正在按下另一个光标键。

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

您的代码将不会起作用:

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

,因为这不可能是真的。 KeyCode是一个单一的关键代码,它不能是一个关键和另一个。

+0

当两个光标键被按下时,你能编码对象的对角线移动吗? – conquistador 2013-03-09 09:21:07

+0

@XtraCode没有任何时间(我远离我的开发系统)。 – Richard 2013-03-09 09:22:02