Detecting USB Insertion / Removal Events in Windows using C++

感情迁移 提交于 2019-11-27 07:27:48

Create a dummy window that does nothing but wait for WM_DEVICECHANGE and register that window using RegisterDeviceNotification. WMI is an overkill here, IMHO.

There is a MSDN sample specifically for your case, in native code.

Registering for Device Notification

Better to do it this way than via WMI.

I followed your "new approach" and also found that OnDeviceChange wasn't being called. The problem was that there was no message loop because it was a Console app. Calling the following function at regular intervals fixed it.

void check_for_device_change()
{
    MSG msg; 

    const int val = PeekMessage( &msg, 0, 0, 0, PM_REMOVE );

    if( val > 0 )
    { 
        TranslateMessage( &msg );
        DispatchMessage( &msg );
    } 
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!