Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleDetect when the user presses arrow keys (could be used for a game)
DescriptionThis example shows how to detect when the user presses arrow keys (could be used for a game) in Visual Basic 6. This program uses KeyDown and KeyUp event handlers to keep track of which keys are up or down.
Keywordsarrow keys, detect keys, keys
CategoriesMiscellany
 
Thanks to Mariano Birnios.

The main form's KeyPreview is True so its KeyDown and Keyup event handlers get keyboard events. Those event handlers set a value in an array to indicate whether a key is up or down.

One odd case that this handles is when the user presses multiple keys. The array will know if the user is holding down the Left and Up arrows at the same time.

 
'This vector contains the state of all keys
'I think KeyCode goes from 0 to 255, but you
'can change this if you want
Dim Keys(255) As Boolean

'Its used to stop the Do-Loop of the Form_Load
Dim StopLoop As Boolean

Private Sub Form_KeyDown(KeyCode As Integer, Shift As _
    Integer)
   'The key KeyCode is pressed now...
   Keys(KeyCode) = True
End Sub

Private Sub Form_KeyUp(KeyCode As Integer, Shift As Integer)
   'The key KeyCode is NOT pressed now...
   Keys(KeyCode) = False
End Sub

Private Sub Form_Load()
Dim str As String

   Me.Show

   'The form must handle the key events
   Me.KeyPreview = True

   StopLoop = False

   Do
      'Just check for the arrow keys to see
      'if they are pressed. To check form more
      'keys, just ask for the correct subindex
      'in the "Keys" array
      str = ""

      If Keys(vbKeyUp) Then str = str + "UP" & vbCrLf
      If Keys(vbKeyDown) Then str = str + "DOWN" & vbCrLf
      If Keys(vbKeyLeft) Then str = str + "LEFT" & vbCrLf
      If Keys(vbKeyRight) Then str = str + "RIGHT" & vbCrLf

      'Refresh the label
      lblKeys = str

      'Important!! (to not freeze the thing)
      DoEvents
   Loop Until StopLoop
End Sub

Private Sub Form_Unload(Cancel As Integer)
   'Important!! To stop the loop, so the
   'form can be unloaded
   StopLoop = True
End Sub
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated