2013-03-09 33 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