USB插拔检测程序
一、手动添加ON_WM_DEVICECHANGE()消息
二、添加头文件#include <Dbt.h>
三、定义设备的GUID
static const GUID GUID_DEVINTERFACE_LIST[] =
{
// GUID_DEVINTERFACE_USB_DEVICE USB设备的GUID
{ 0xA5DCBF10, 0x6530, 0x11D2, { 0x90, 0x1F, 0x00, 0xC0, 0x4F, 0xB9, 0x51, 0xED } }
};
四、注册设备,只有注册了该设备,OnDeviceChange才能获得详细的信息,否则收到的nEventType参数都是0007,dwData无数据。
HDEVNOTIFY hDevNotify;
for (int i = 0; i < sizeof(GUID_DEVINTERFACE_LIST) / sizeof(GUID); i++)
{
DEV_BROADCAST_DEVICEINTERFACE NotificationFilter;
ZeroMemory(&NotificationFilter, sizeof(NotificationFilter));
NotificationFilter.dbcc_size = sizeof(DEV_BROADCAST_DEVICEINTERFACE);
NotificationFilter.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE;
NotificationFilter.dbcc_classguid = GUID_DEVINTERFACE_LIST[i];
hDevNotify = RegisterDeviceNotification(this->GetSafeHwnd(), &NotificationFilter, DEVICE_NOTIFY_WINDOW_HANDLE);
if( !hDevNotify )
{
AfxMessageBox(CString("Can't register device notification: ")
+ _com_error(GetLastError()).ErrorMessage(), MB_ICONEXCLAMATION);
return FALSE;
}
}
五、添加消息响应函数
声明:afx_msg BOOL OnDeviceChange(UINT nEventType, DWORD dwData);
定义:
BOOL CDeviceChangeDlg::OnDeviceChange(UINT nEventType,DWORD dwData)
{
DEV_BROADCAST_DEVICEINTERFACE* dbd = (DEV_BROADCAST_DEVICEINTERFACE*) dwData;
//针对各个事件进行处理.
switch (nEventType)
{
case DBT_DEVICEREMOVECOMPLETE:
AfxMessageBox(_T("设备移除"));
break;
case DBT_DEVICEARRIVAL:
AfxMessageBox(_T("设备接入"));
break;
default:
break;
}
return TRUE;
}
note:
源码请参考:https://download.csdn.net/download/qq_23565865/10809685
---------------------
作者:小雨滴答滴答
来源:CSDN
原文:https://blog.csdn.net/qq_23565865/article/details/84561017
版权声明:本文为博主原创文章,转载请附上博文链接!