Make your own free website on Tripod.com
Allow The User To Press Unlimited Number Of Keys At The Same Time

This example is very useful for games programming, where the user, for example, move an object and fire or jump at same time.
The code below will tell you what keys are currently being pressed: Up, Down, Left, Right and Space.
Of course you can easily change this code to apply other keys.

Note that if you use the arrow keys, instead of the keyPad Keys (the keys with numbers and arrows, that the numlock key transform them from arrow keys to number keys), you will be able to determine only what the last two keys that being pressed.

Preparations

Add 5 Labels to your form.

Form Code

'currectKeys array holds all the currently pressed keys.
'For example, if Space Bar is the only pressed key, currentKeys(32) value will
'be True (because Space Bar keyCode is 32) and all the others array's values will
'be False.

Dim currentKeys(0 To 250) As Boolean

Private Sub Form_KeyDown(KeyCode As Integer, Shift As Integer)
'Pressing a key and holding it down, will launch the KeyDown event over
'and over again. so we check if the user just pressed the key, or the key
'is already down.

    If currentKeys(KeyCode) = False Then
'Update the array that the current key has been pressed.
        currentKeys(KeyCode) = True
        If KeyCode = vbKeyLeft Then Label1 = "Left"
        If KeyCode = vbKeyRight Then Label2 = "Right"
        If KeyCode = vbKeyUp Then Label3 = "Up"
        If KeyCode = vbKeyDown Then Label4 = "Down"
        If KeyCode = vbKeySpace Then Label5 = "Fire"
    End If
End Sub

Private Sub Form_KeyUp(KeyCode As Integer, Shift As Integer)
'Update the array that the current key is no longer being pressed.

    currentKeys(KeyCode) = False
    If KeyCode = vbKeyLeft Then Label1 = ""
    If KeyCode = vbKeyRight Then Label2 = ""
    If KeyCode = vbKeyUp Then Label3 = ""
    If KeyCode = vbKeyDown Then Label4 = ""
    If KeyCode = vbKeySpace Then Label5 = ""
End Sub

Private Sub Form_Load()
'Initialize labels text
    Label1 = ""
    Label2 = ""
    Label3 = ""
    Label4 = ""
    Label5 = ""
End Sub

Go Back