Qt Usb插拔检测

Qt Usb插拔检测

第一步 注册设备通知到窗口:

BOOL CHid::RegisterHidDeviceNotify(/*HWND hWnd, HDEVNOTIFY hDevNotify*/)	//HDEVNOTIFY结构需要在StdAfx.h中定义#deinfe WINVER 0x0500 
{
	GUID HidGuid;										/* temporarily stores Windows HID Class GUID */
	DEV_BROADCAST_DEVICEINTERFACE NotificationFilter;	/* un/plug notification filter */

	/* Set up device notification (i.e. plug or unplug of HID Devices) */
	
	/* 1) get the HID GUID */
	HidD_GetHidGuid(&HidGuid);
				
	/* 2) clear the notification filter */
	ZeroMemory( &NotificationFilter, sizeof(NotificationFilter));
				
	/* 3) assign the previously cleared structure with the correct data
	so that the application is notified of HID device un/plug events */
	NotificationFilter.dbcc_size = sizeof(DEV_BROADCAST_DEVICEINTERFACE);
	NotificationFilter.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE;
	NotificationFilter.dbcc_classguid = HidGuid;
				


	/* 4) register device notifications for this application */
	m_hDevNotify = RegisterDeviceNotification(	m_hParentWnd,
												&NotificationFilter, 
												DEVICE_NOTIFY_WINDOW_HANDLE);

	/* 5) notify the calling procedure if the HID device will not be recognized */
	if(!m_hDevNotify)
		return FALSE;

	return TRUE;
}
其中 RegisterDeviceNotification 中的m_hParentWnd 换成(HWND *)(this->winID())。

第二步 重写winEvent(MSG *msg, long *result)函数:

bool GMotion::winEvent(MSG *msg, long *result)
{
	bool bResult = false;
	PDEV_BROADCAST_HDR lpdb = (PDEV_BROADCAST_HDR)msg->lParam;

	switch(msg->wParam)
	{
	case DBT_DEVICEARRIVAL:
		/*TODO*/
		bResult = true;
		break;

	case DBT_DEVICEREMOVECOMPLETE:
		/*TODO*/
		bResult = true;
		break;

	case DBT_DEVNODES_CHANGED:
		/*TODO*/
		bResult = true;
		break;

	default:
		/*TODO*/
		bResult = false;
		break;
	}

	return bResult;
}
在相应的case里面添加处理函数。

你可能感兴趣的:(Qt)