You may use the
SetupDiGetClassDevsEx [
^] Setup API function to retrieve information on keyboards and mouses (you may connect more than one of each).
To detect arrival or removal of devices (including mouse and keyboard), you can add a
WM_DEVICECHANGE [
^] handler to your app.
[UPDATE: Example code]
When using MFC, add the
WM_DEVICECHANGE
handler to your main frame class (or the main dialog with dialog apps). With Win32 apps, handle the message in the message loop of your main window/app. The
wParam
is the event type and the
lParam
is the data pointer.
#include <dbt.h>
ON_WM_DEVICECHANGE()
int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CMDIFrameWnd::OnCreate(lpCreateStruct) == -1)
return -1;
DEV_BROADCAST_DEVICEINTERFACE Notify;
::ZeroMemory(&Notify, sizeof(DEV_BROADCAST_DEVICEINTERFACE));
Notify.dbcc_size = sizeof(DEV_BROADCAST_DEVICEINTERFACE);
Notify.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE;
const GUID GUID_DEVINTERFACE_HDI =
{ 0x4d1e55b2, 0xf16f, 0x11cf, { 0x88, 0xcb, 0x00, 0x11, 0x11, 0x00, 0x00, 0x30}};
Notify.dbcc_classguid = GUID_DEVINTERFACE_HDI;
ASSERT(this->GetSafeHwnd());
HDEVNOTIFY hDevNotify = ::RegisterDeviceNotification(
this->GetSafeHwnd(),
&Notify,
DEVICE_NOTIFY_WINDOW_HANDLE);
ASSERT(HDEVNOTIFY);
return 0;
}
BOOL CMainFrame::OnDeviceChange(UINT nEventType, DWORD_PTR dwData)
{
BOOL nResult = CMDIFrameWnd::OnDeviceChange(nEventType, dwData);
if (nEventType == DBT_DEVICEARRIVAL || nEventType == DBT_DEVICEREMOVECOMPLETE)
{
TRACE1("WM_DEVICECHANGE event %#X\n", nEventType);
PDEV_BROADCAST_HDR pHdr = reinterpret_cast<PDEV_BROADCAST_HDR>(dwData);
if (pHdr->dbch_devicetype == DBT_DEVTYP_DEVICEINTERFACE)
{
PDEV_BROADCAST_DEVICEINTERFACE pDev =
reinterpret_cast<PDEV_BROADCAST_DEVICEINTERFACE>(dwData);
TRACE2("%s %s\n",
nEventType == DBT_DEVICEARRIVAL ? "Arrival of" : "Removed",
pDev->dbcc_name);
TCHAR lpszBuf[256];
if (::StringFromGUID2(pDev->dbcc_classguid, lpszBuf, 256))
TRACE1("GUID: %s\n", lpszBuf);
}
}
return nResult;
}
Example output when removing and inserting USB mouse:
WM_DEVICECHANGE event 0X8004
Removed \\?\HID#VID_046D&PID_C018#6&1e99df8d&0&0000#{4d1e55b2-f16f-11cf-88cb-001111000030}
GUID: {4D1E55B2-F16F-11CF-88CB-001111000030}
WM_DEVICECHANGE event 0X8000
Arrival of \\?\HID#VID_046D&PID_C018#6&1e99df8d&0&0000#{4d1e55b2-f16f-11cf-88cb-001111000030}
GUID: {4D1E55B2-F16F-11CF-88CB-001111000030}