MFC C++ differentiate between two devices from WM_DEVICECHANGE notifications

Viewed 318

I am coding a function to detect addition/removal of USB devices using C++ VS2019 in windows. WM_DEVICECHANGE gives notification when a device is removed or connected to PC, but it gives multiple notifications for a single device. The parameters that are returned through are also same for all notifications.

The problem is When 2 devices are connected or removed just one after another, the number of notifications increases but the parameters remains the same. How can i differentiate that the notifications are from different devices.

BEGIN_MESSAGE_MAP(CCheckDlg, CDialogEx)
   ON_MESSAGE(WM_DEVICECHANGE, &CCheckDlg::OnMyDeviceChange)
END_MESSAGE_MAP()

The function:

    LRESULT CCheckDlg::OnMyDeviceChange(WPARAM wParam, LPARAM lParam)
    {
        //When USB device connected or removed,
        //The wParam is always equal to 7 and lParam is equal to 0.
    }

Or, if there is any other way to detect device addition/removal using C++, you can suggest.

Thank you.

1 Answers

The wParam of the WM_DEVICECHANGE message contains the particular event that triggered this message. A value of 7 refers to the DBT_DEVNODES_CHANGED event.

The documentation for DBT_DEVNODES_CHANGED explains:

There is no additional information about which device has been added to or removed from the system. Applications that require more information should register for device notification using the RegisterDeviceNotification function.

Related