怎么捕获非标准usb设备插入或拔出消息? 收藏
我用mfc开发,用OnDeviceChange(UINT nEventType,DWORD_PTR dwData)消息回调函数来处理消息,但是一个奇怪的问题就是某些非标准usb设备(比如一些电子钥匙),插入或拔出的时候始终只发送 DBT_DEVNODES_CHANGED消息(即nEventType== 7),而且dwData始终为0;但是如果插入一些普通U盘,就可以截获到DBT_DEVICEARRIVAL、 DBT_DEVICEREMOVECOMPLETE等消息。这是怎么回事那?
另外,我想滤除其它usb设备插入与拔出时产生的DBT_DEVNODES_CHANGED消息,我该怎么办?一定要写过滤驱动程序吗?还有其它办法没有?
多谢多谢!并祝愿大家十一和中秋双节快乐!
告诉你吧,这个得自己注册事件
BOOL CRSDlg::DoRegisterDeviceInterface(GUID InterfaceClassGuid, HDEVNOTIFY *hDevNotify)
{
DEV_BROADCAST_DEVICEINTERFACE NotificationFilter;
DWORD Err;
ZeroMemory( &NotificationFilter, sizeof(NotificationFilter) );
NotificationFilter.dbcc_size = 32;
// sizeof(DEV_BROADCAST_DEVICEINTERFACE);
NotificationFilter.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE;
NotificationFilter.dbcc_classguid = InterfaceClassGuid;
*hDevNotify = RegisterDeviceNotification(GetSafeHwnd(), &NotificationFilter,
DEVICE_NOTIFY_WINDOW_HANDLE );
if(!*hDevNotify)
{
Err = GetLastError();
CString str;
str.Format(_T(“RegisterDeviceNotification failed: %lx.”),Err);
DT((LPCSTR)str);
return FALSE;
}
DT(“RegisterDeviceNotification Successed
”);
//UnregisterDeviceNotification(*hDevNotify);
return TRUE;
}
检测 DBT_DEVNODES_CHANGED 要调用一下专用设备的SDK
Scanning for attached USB devices:
USB Device 0: VendorID: 0×0451 ProductID 0×9001
OnDeviceChange message: 00000007 (DBT_DEVNODES_CHANGED)
OnDeviceChange message: 00000007 (DBT_DEVNODES_CHANGED)
Device successfully opened.
Get current device parameters was successful.
OnDeviceChange message: 00000007 (DBT_DEVNODES_CHANGED)
void USB_event::RegisterNotification()
{
DEV_BROADCAST_DEVICEINTERFACE devIF = {0};
devIF.dbcc_size = sizeof(devIF);
devIF.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE;
devIF.dbcc_classguid = GUID_INTERFACE_CP210x; //MY_DEVICE_GUID;
m_hNotifyDevNode = RegisterDeviceNotification(window_ptr->winId(),
&devIF, DEVICE_NOTIFY_WINDOW_HANDLE);
}
The GUID looks like this:
DEFINE_GUID(GUID_INTERFACE_CP210x, 0×993f7832, 0×6e2d, 0×4a0f, 0xb2, 0×72,
0xe2, 0xc7, 0×8e, 0×74, 0xf9, 0×3e);
Code Snippet
protected override void OnSourceInitialized(EventArgs e)
{
base.OnSourceInitialized(e);
HwndSource hwndSource = PresentationSource.FromVisual(this) as HwndSource;
if (hwndSource != null)
{
hwndSource.AddHook(new HwndSourceHook(this.hwndSourceHook));
}
}
IntPtr hwndSourceHook(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
if (msg == Win32.WM_DEVICECHANGE)
{
if ((int)wParam == Win32.DBT_DEVICEARRIVAL)
{
RaiseDeviceArrived();
}
else if ((int)wParam == Win32.DBT_DEVICEREMOVECOMPLETE)
{
RaiseDeviceRemoved();
}
}
return IntPtr.Zero;
}
历史博文
- 20070118 .net 源码 - 2008
- 20070527 SaferRun 1.00 - 2007
- 0516 svn authz 认证 - 2006
- PHP MYSQL 通用数据处理 AJAX WINDOWS - 2005