DirectX SDK |
This topic pertains only to application development in Visual Basic. See DirectInput C/C++ Tutorials.
Once a device is acquired, your application can start retrieving data from it. The simplest way to do this is to call the DirectInputDevice.GetDeviceStateKeyboard method, which takes a snapshot of the device's state at the time of the call.
The GetDeviceStateKeyboard method accepts as its single parameter a DIKEYBOARDSTATE type, which simply contains an array of 256 bytes.
The following sample retrieves the state of the keyboard:
Dim state As DIKEYBOARDSTATE Call didev.GetDeviceStateKeyboard(state)
After retrieving the keyboard's current state, your application may respond to specific keys that were down at the time of the call. Each element in the buffer represents a key. If an element's high bit is on, the key was down at the moment of the call; otherwise, the key was up. To check the state of a given key, use the constants of the CONST_DIKEYFLAGS enumeration to index the buffer for a given key.
The following sample code shows how an application might move a vehicle around in response to the arrow keys:
If state.Key(DIK_UP) And &H80 Then ' Move the vehicle up End If if state.Key(DIK_DOWN) And &H80 Then ' Move the vehicle down End If ' And so on.
The following works just as well:
If state.Key(DIK_UP) ' Move the vehicle up End If
The value of the key state is 0 if the key is up, as is the case with all buttons in the current version of DirectInput. However, future versions might support "analog" keys with more than two states and hence more than a single nonzero value, so this shorter version of the code should be used with caution, especially for devices other than the keyboard.
Remember also that DIK_UP is a single key, the dedicated up arrow key. DirectInput treats the 8 key on the numerical keypad as a distinct key, and gives it the same identifier regardless of whether NUM LOCK is on. In order to allow input from either of the arrow keys, you would have to write code like this:
If state.Key(DIK_UP) Or state.Key(DIK_NUMPAD8) Then ' Move the vehicle up End If