1. 程式人生 > >QT程式設計--監聽USB裝置拔出和插入。

QT程式設計--監聽USB裝置拔出和插入。


第一步過載函式winEvent(),5.6.0版本是nativeEvent(),如下:
bool Dialog_XXX::nativeEvent(const QByteArray &eventType, void *message, long *result)
{
	if (eventType == "windows_generic_MSG")
	{

		bool bResult = false;

		MSG* msg = reinterpret_cast<MSG*>(message);

		PDEV_BROADCAST_HDR lpdb = (PDEV_BROADCAST_HDR)msg->lParam;

		if(msg->message == WM_DEVICECHANGE && msg->wParam >= DBT_DEVICEARRIVAL)
		{ 
			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;
	}
	else
	{
		return QWidget::nativeEvent(eventType, message, result);
	}
		
}

第二步,註冊裝置,如果不註冊則檢測不到DBT_DEVICEARRIVAL和DBT_DEVICEREMOVECOMPLETE。
	DEV_BROADCAST_DEVICEINTERFACE NotificationFilter;
	ZeroMemory(&NotificationFilter, sizeof(NotificationFilter));
	NotificationFilter.dbcc_size = sizeof(DEV_BROADCAST_DEVICEINTERFACE);
	NotificationFilter.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE;
	// assume we want to be notified with USBSTOR
	// to get notified with all interface on XP or above
	// ORed 3rd param with DEVICE_NOTIFY_ALL_INTERFACE_CLASSES and dbcc_classguid will be ignored
	NotificationFilter.dbcc_classguid = GUID_DEVINTERFACE_USBSTOR;
	RegisterDeviceNotification((HANDLE)this->winId(), &NotificationFilter, DEVICE_NOTIFY_WINDOW_HANDLE);