Step 4: Setting the Keyboard Behavior

Before your application can gain access to the keyboard, it must set the device's behavior using the IDirectInputDevice::SetCooperativeLevel method, as shown in Sample Function 1: DI_Init. This method accepts the handle to the window to be associated with the device. DirectInput does not support exclusive access to keyboard devices, so the DISCL_NONEXCLUSIVE flag must be included in the dwFlags parameter.

The following example attempts to set the device's cooperative level. If this fails, it calls the DI_Term application-defined sample function to deallocate existing DirectInput objects, if any.

// Set the cooperative level 
hr = g_lpDIDevice->SetCooperativeLevel(g_hwndMain, 
                   DISCL_FOREGROUND | DISCL_NONEXCLUSIVE); 
 
if FAILED(hr){ 
    DI_Term(); 
    return FALSE; 
}