Keyboard input


We can easily detect what keys the user is pressing on the keyboard using one of Visual Basics built in events. Detecting what keys are pressed is very useful in games where you may want to have them move something with the arrow keys.

Keyboard input


First we should set the Forms property so that it automatically gets any keypress information sent to it. Otherwise the keypress information may be sent to buttons etc.

Now create a label, which we will move around in the example, remove the caption or call it somethign like car and set its background color to red/blue/yellow (so that it shows up). Name the label 'car'.

Now we have completed the graphical side of the little project we can go onto the main part which is the coding.

The Code


Double click the form and you will find that you get its Load event. To change this go to the drop down box in the upper right hand corner of the code window and select 'KeyDown' from it. This should give you the forms KeyDown event. Now we are going to use a select case. A select is just an easy way of doing lots of Ifs. We could use Ifs here but as you will see a Select case is a lot easier. With a Select you choose a variable and then with each case you see whether the variable has a certain value. It is easier when you see one so there is the example below.

The KeyCode variable, which is declared in the brackets at the top, will contain a number. The number is just a number given to a certain key. In VB there are some predefined variables that save you learning or looking up the values for every key. These can be called the key constants. They all start with 'vbKey' and then they have the key name after it. For example: vbKeyUp, vbKeyA, vbKeyReturn etc. We just see if the returned value is the same as the key constant we are checking.

Here is the example code:
Private Sub Form_KeyDown(KeyCode As Integer, Shift As Integer)
Select Case KeyCode
Case vbKeyUp
    Car.Top = Car.Top - 100
Case vbKeyDown
    Car.Top = Car.Top + 100
Case vbKeyRight
    Car.Left = Car.Left + 100
Case vbKeyLeft
    Car.Left = Car.Left - 100
End Select
End Sub


© Jonathan Waller 2005; QuantumState Visual Basic