Microsoft DirectX 8.1 (Visual Basic)

Step 2: Setting the Keyboard Parameters

After creating a DirectInputDevice8, your application must set the device's data format. For keyboards, as with other standard devices, this is a very simple task. Call the DirectInputDevice8.SetCommonDataFormat method, specifying the data format provided by Microsoft® DirectInput® by using the DIFORMAT_KEYBOARD constant as the parameter. You must set the data format even if you intend to retrieve buffered data.

Call didev.SetCommonDataFormat(DIFORMAT_KEYBOARD) 
 

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 DirectInputDevice8.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 (either DISCL_EXCLUSIVE or DISCL_NONEXCLUSIVE, plus either DISCL_FOREGROUND or DISCL_BACKGROUND), indicating the desired cooperative level. However, DirectInput does not support exclusive access to keyboard devices, so the DISCL_NONEXCLUSIVE flag must always be used in the case of keyboards as it is here.

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.

Now that the keyboard device has been created and set up, it must be acquired. This is shown in Step 3: Gaining Access to the Keyboard.