Platform SDK: DirectX

Step 2: Set the Keyboard Parameters

[C++]

This topic pertains only to application development in Visual Basic. See DirectInput C/C++ Tutorials.

[Visual Basic]

After creating a DirectInputDevice, your application must set the device's data format. For keyboards, as with other standard devices, this is a very simple task. Call the DirectInputDevice.SetCommonDataFormat method, specifying the data format provided for your convenience by DirectInput when you pass DIFORMAT_KEYBOARD as the parameter.

Call didev.SetCommonDataFormat(DIFORMAT_KEYBOARD) 
 

Remember, you have to set the data format even if you intend to retrieve buffered data. DirectInput identifies the device objects by their offset within the data format. In the case of the keyboard, keys are identified by their offsets within the DIKEYBOARDSTATE type.

Before your application can gain access to the keyboard, it must set the device's behavior using the DirectInputDevice.SetCooperativeLevel method, as follows:

didev.SetCooperativeLevel Me.hWnd, _
        DISCL_NONEXCLUSIVE Or DISCL_BACKGROUND
 

This method accepts the handle to the window to be associated with the device, and exactly two flags (one of DISCL_EXCLUSIVE and DISCL_NONEXCLUSIVE, and one of DISCL_FOREGROUND and DISCL_BACKGROUND), indicating the desired cooperative level. DirectInput does not support exclusive access to keyboard devices, so the DISCL_NONEXCLUSIVE flag must be included in this case.

The example also sets the background cooperative level, so input will be available regardless of whether the form is in the foreground. Note also that keystrokes continue to be passed through to whatever application has the focus. Most applications don't need input when they're in the background, and in such cases the DISCL_FOREGROUND flag should be set instead.

Next: Step 3: Gain Access to the Keyboard