Creating a DirectInput Device

The IDirectInput::CreateDevice method is used to obtain a pointer to the IDirectInputDevice interface. Methods of this interface are then used to manipulate the device and obtain data.

The following example, where lpdi is a pointer to the IDirectInput interface, creates a keyboard device:

LPDIRECTINPUTDEVICE  lpdiKeyboard; 
lpdi->CreateDevice(GUID_SysKeyboard, &lpdiKeyboard, NULL); 
 

The first parameter in IDirectInput::CreateDevice is an instance GUID that identifies the instance of the device for which the interface is to be created. DirectInput has two predefined GUIDs, GUID_SysMouse and GUID_SysKeyboard, which represent the system mouse and keyboard, and you can pass these identifiers into the CreateDevice method. The global variable GUID_Joystick should not be used as a parameter for CreateDevice, because it is a product GUID, not an instance GUID.

Note  If the workstation has more than one mouse, input from all of them is combined to form the system device. The same is true for multiple keyboards.

For devices other than the system mouse or keyboard, use the instance GUID for the device returned by IDirectInput::EnumDevices. The instance GUID for a device will always be the same. You can allow the user to select a device from a list of those enumerated, then save the GUID to a configuration file and use it again in future sessions.

If you want to use the IDirectInputDevice2 interface methods for force-feedback devices, you must obtain a pointer to that interface instead of IDirectInputDevice. The following function is a wrapper for the CreateDevice method that attempts to obtain the IDirectInputDevice2 interface. Note the use of macros to call the Release and CreateDevice methods according to either the C or C++ syntax.

HRESULT IDirectInput_CreateDevice2(LPDIRECTINPUT pdi, 
                                   REFGUID rguid, 
                                   LPDIRECTINPUTDEVICE2 *ppdev2, 
                                   LPUNKNOWN punkOuter) 
{ 
    LPDIRECTINPUTDEVICE *pdev; 
    HRESULT hres; 
 
    hres = IDirectInput_CreateDevice(pdi, rguid, &pdev, punkOuter);
 
    if (SUCCEEDED(hres)) { 
#ifdef __cplusplus 
    hres = pdev->QueryInterface(IID_IDirectInputDevice2, 
                                    (LPVOID *)ppdev2); 
#else 
    hres = pdev->lpVtbl->QueryInterface(pdev, 
                       &IID_IDirectInputDevice2, 
                              (LPVOID *)ppdev2); 
#endif 
    IDirectInputDevice_Release(pdev); 
    } else { 
    *ppdev2 = 0; 
    } 
    return hres; 
}