其他分享
首页 > 其他分享> > winform 实现对usb热拔插的监听

winform 实现对usb热拔插的监听

作者:互联网

本文参考链接

https://www.cnblogs.com/gsk99/p/4983043.html
https://blog.csdn.net/z0582/article/details/7328290
https://docs.microsoft.com/en-us/windows/win32/devio/registering-for-device-notification

 

最近因为一个项目需要跟硬件打交道,所以需要监听存储设备的事件。看了很多资料,最有用的还是上面的三个篇,故此分享出来

Windows消息有两种监听方式:

  1.通过服务的方式监听(未涉及)

  2.通过窗体的方式监听(本例)

 

在demo中,可能很多人会疑惑

            public const int WM_DEVICECHANGE = 537;
            /// BROADCAST_QUERY_DENY -> 0x424D5144
            //public const int BROADCAST_QUERY_DENY = 1112363332;
            //public const int DBT_DEVTYP_DEVICEINTERFACE = 5;
            //public const int DBT_DEVTYP_HANDLE = 6;
            public const int DBT_DEVICEARRIVAL = 0x8000; // system detected a new device
                                                         //public const int DBT_DEVICEQUERYREMOVE = 0x8001;   // Preparing to remove (any program can disable the removal)
            public const int DBT_DEVICEREMOVECOMPLETE = 0x8004; // removed 
            public const int DBT_DEVTYP_VOLUME = 0x00000002; // drive type is logical volume

  这里的值,比如 “0x8000” 的值是怎么来的?

  就需要查看微软的官方手册,比如,我们是需要实现监听usb的功能,就看官方的代码

  https://docs.microsoft.com/en-us/windows/win32/devio/registering-for-device-notification

……
// Output some messages to the window. switch (wParam) { case DBT_DEVICEARRIVAL: msgCount++; StringCchPrintf( strBuff, 256, TEXT("Message %d: DBT_DEVICEARRIVAL\n"), (int)msgCount); break; case DBT_DEVICEREMOVECOMPLETE: msgCount++; StringCchPrintf( strBuff, 256, TEXT("Message %d: DBT_DEVICEREMOVECOMPLETE\n"), (int)msgCount); break; case DBT_DEVNODES_CHANGED: msgCount++; StringCchPrintf( strBuff, 256, TEXT("Message %d: DBT_DEVNODES_CHANGED\n"), (int)msgCount); break; default: msgCount++; StringCchPrintf( strBuff, 256, TEXT("Message %d: WM_DEVICECHANGE message received, value %d unhandled.\n"), (int)msgCount, wParam); break; }
……

  我们要查看设备刚刚连接时的值,其实就是  DBT_DEVICEARRIVAL 的枚举。查看定义的时候,能看到具体定义的值

……
#define DBT_DEVICEARRIVAL 0x8000 // system detected a new device #define DBT_DEVICEQUERYREMOVE 0x8001 // wants to remove, may fail #define DBT_DEVICEQUERYREMOVEFAILED 0x8002 // removal aborted #define DBT_DEVICEREMOVEPENDING 0x8003 // about to remove, still avail. #define DBT_DEVICEREMOVECOMPLETE 0x8004 // device is gone #define DBT_DEVICETYPESPECIFIC 0x8005 // type specific event
……

 

  如果还想实现对windows其它事件的监听处理,只需要查到对应编码,然后处理相关事件即可。

 

项目的demo地址:

标签:msgCount,const,usb,int,public,热拔,define,DBT,winform
来源: https://www.cnblogs.com/everydaygift/p/14103825.html