Platform SDK: DirectX

Recognizing Device Changes

[Visual Basic]

This topic pertains only to applications written in C++.

[C++]

Because universal serial bus (USB) devices can be added to and removed from the system without rebooting, you might want your application to be able to respond to a new configuration of input devices. For example, you might allow a new player to join a game in progress by plugging in another controller.

To receive a message when a device is changed, you must first register for notification, as in the following code example:

PVOID hNotifyDevNode;
 
void RegisterForDevChange(HWND hDlg, PVOID *hNotifyDevNode)
{
    DEV_BROADCAST_DEVICEINTERFACE *pFilterData = 
           (DEV_BROADCAST_DEVICEINTERFACE*) 
           _alloca(sizeof(DEV_BROADCAST_DEVICEINTERFACE));
    ASSERT (pFilterData);
 
    ZeroMemory(pFilterData, sizeof(DEV_BROADCAST_DEVICEINTERFACE));
 
    pFilterData->dbcc_size = sizeof(DEV_BROADCAST_DEVICEINTERFACE);
    pFilterData->dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE;
    pFilterData->dbcc_classguid  = GUID_CLASS_INPUT; 
 
    *hNotifyDevNode = RegisterDeviceNotification(hDlg, pFilterData,
            DEVICE_NOTIFY_WINDOW_HANDLE);
}

Then, in your main window procedure, check for messages announcing that a device has been attached, is about to be removed, or has been removed, as follows:

MyWindowProc(HWND hWnd, UINT nMsg, WPARAM wParam, LPARAM lParam)
{
    switch (nMsg)
    {
        case WM_DEVICECHANGE:
        {
            switch (wParam)
            {
                case DBT_DEVICEARRIVAL:
                    // Handle device arrival
                    break;

                case DBT_DEVICEQUERYREMOVE:
                    // Handle device removal request
                    break;
                
                case DBT_DEVICEREMOVECOMPLETE:
                    // Handle device removal
                    break;
            }
        }
.
.
.
    }
}

In response to a DBT_DEVICEARRIVAL event, obtain the instance GUID of the device by using IDirectInput7::FindDevice, and pass this value to IDirectInput7::CreateDeviceEx.

For more information, see Device Management in the the Platform SDK.