Version 2.0!
Features
Tutorials
Files
Glossary
Projects
Contact
Links
Message Board
Extras
LuckyCam
Old News
Sign Guestbook
View Guestbook
VB Horoscope
VB Photo Album
.
ATTENTION READERS! Lucky's VB Gaming Site is no longer active. For updated game programming information and tutorials, please visit The Game Programming Wiki!

Direct Input

Direct Input is a component of DirectX that gives you direct access to the current state of the keyboard (among other devices). This is obviously quite useful for game programming purposes and so I will outline its use here.

Dim dx As New DirectX7
Dim di As DirectInput
Dim diDEV As DirectInputDevice

    Set di = dx.DirectInputCreate()
    Set diDEV = di.CreateDevice("GUID_SysKeyboard")

    diDEV.SetCommonDataFormat DIFORMAT_KEYBOARD
    diDEV.SetCooperativeLevel Me.hWnd, DISCL_BACKGROUND Or DISCL_NONEXCLUSIVE
    diDEV.Acquire

As with DirectDraw, we have to create an instance of the DirectX7 object and use it to define a DirectInput object, "di". We then need to set the direct input device to the one in which we are interested, in this case the keyboard. So, we call the "di.CreateDevice" method and request it returns the system keyboard object.

Next we have to set the data format of the device to the keyboard data format. We do this with the "diDEV.SetCommonDataFormat". We could also use this to set the data format to Joy1, Joy2, or the mouse.

Just like DirectDraw, we must set the cooperative level. We pass the handle to the window for which we would like to receive keyboard input, if this is the form in which the code resides we can pass "Me.hWnd". "DISCL_BACKGROUND" and "DISCL_NONEXCLUSIVE" allows other programs access to keystrokes, and give us access to all keystrokes.

Now that we've set up the device which we'd like to use, we have to acquire it using the "diDEV.Acquire" method.

Dim diState As DIKEYBOARDSTATE
Dim i As Integer
Public aKeys(211) As Boolean

    diDEV.GetDeviceStateKeyboard diState

    For i = 1 To 211

      If diState.Key(i) <> 0 Then
        aKeys(i) = True
      Else
        aKeys(i) = False
      End If
    Next

Everything is setup, now we can reap what we have sown (no, I'm not suggesting you go plant your keyboard in your garden in order to cultivate input). "diState" is an object that will contain the states of all the keys on the keyboard, and we can tap into this using an array and a loop. Each key on the keyboard corresponds to an integer value between 0 and 211. If we then make an array with 212 members we can keep track of which keys are active and when. Use the "diDEV.GetDeviceStateKeyboard" method to fill the "diState" variable, and then extract the data from this into our array "aKeys" using a "for" loop.

Have a look at my DirectX 7 sample project to see which keypress corresponds to which value and to see DirectInput in action.