Wyo VB Lecture Notes
Objective #1: Be able to use the KeyDown & KeyPress methods.
If (e.KeyCode = Keys.Right Or e.KeyCode = Keys.D or e.KeyCode = Keys.NumPad6)
Then
picPlayer.Left = picPlayer.Left + 5
ElseIf (e.KeyCode = Keys.Left Or e.KeyCode = Keys.A or e.KeyCode = Keys.NumPad4) Then
picPlayer.Left = picPlayer.Left - 5
ElseIf (e.KeyCode = Keys.Up Or e.KeyCode = Keys.W or e.KeyCode = Keys.NumPad8) Then
picPlayer.Top = picPlayer.Top - 5
ElseIf (e.KeyCode = Keys.Down Or e.KeyCode = Keys.S or e.KeyCode = Keys.NumPad2) Then
picPlayer.Top = picPlayer.Top + 5
End If
End Sub
If (e.KeyChar = "d") Then
picPlayer.Left = picPlayer.Left + 1
ElseIf (e.KeyChar = "a") Then
picPlayer.Left = picPlayer.Left - 1
ElseIf (e.KeyChar = "w") Then
picPlayer.Top = picPlayer.Top - 1
ElseIf (e.KeyChar = "s") Then
picPlayer.Top = picPlayer.Top + 1
End If
End Sub
The following technique will not be covered on any tests or quizzes but it may be helpful in projects.
If you have placed a button, Windows Media Player or other object on your form, you may need to set
the form's KeyPreview property to True in
order for the KeyPress method to work correctly. Or, you may need to use the ProcessCmdKey Function rather than the KeyDown or KeyPress methods as demonstrated below.
Protected Overrides Function ProcessCmdKey(ByRef msg As Message, ByVal keyData As Keys) As Boolean
' collision detection in the Maze2 assignment can be placed here
If (keyData = Keys.Right Or keyData = Keys.D or keyData = Keys.NumPad6)
Then
picPlayer.Left = picPlayer.Left + 5
Return True
ElseIf (keyData = Keys.Left Or keyData = Keys.A or keyData = Keys.NumPad4) Then
picPlayer.Left = picPlayer.Left - 5
Return True
ElseIf (keyData = Keys.Up Or keyData = Keys.W or keyData = Keys.NumPad8) Then
picPlayer.Top = picPlayer.Top - 5
Return True
ElseIf (keyData = Keys.Down Or keyData = Keys.S or keyData = Keys.NumPad2) Then
picPlayer.Top = picPlayer.Top + 5
Return True
End If
Return MyBase.ProcessCmdKey(msg, keyData)
End Function