Qt提供了QAbstractNativeEventFilter來實現本地時間得過濾,經過對本地事件的檢測,判斷usb熱插拔;(這裏是windows 的例子);windows
首先,以QWidget, QAbstractNativeEventFilter爲基類創建子類,重定義nativeEventFilter:this
virtual bool nativeEventFilter(const QByteArray &eventType, void *message, long *result);
譬如:創建UDisk類, class UDisk : public QWidget, public QAbstractNativeEventFilter{}blog
bool UDisk::nativeEventFilter(const QByteArray &eventType, void *message, long *result) { MSG* msg = reinterpret_cast<MSG*>(message); int msgType = msg->message; if(msgType == WM_DEVICECHANGE) { // 消息類型, 這裏是設備變更; PDEV_BROADCAST_HDR lpdb = (PDEV_BROADCAST_HDR)msg->lParam; switch (msg->wParam) { case DBT_DEVICEARRIVAL: if(lpdb->dbch_devicetype == DBT_DEVTYP_VOLUME) { PDEV_BROADCAST_VOLUME lpdbv = (PDEV_BROADCAST_VOLUME)lpdb; if(lpdbv->dbcv_flags ==0) { QString USBDisk = QString(this->deviceMask(lpdbv ->dbcv_unitmask)) + ":/"; emit sigUDiskCome(USBDisk); } } break; case DBT_DEVICEREMOVECOMPLETE: if(lpdb->dbch_devicetype == DBT_DEVTYP_VOLUME) { PDEV_BROADCAST_VOLUME lpdbv = (PDEV_BROADCAST_VOLUME)lpdb; if(lpdbv->dbcv_flags == 0) { QString USBDisk = QString(this->deviceMask(lpdbv ->dbcv_unitmask)) +":/"; emit sigUDiskRemove(USBDisk); } } break; case DBT_DEVNODES_CHANGED: break; default: break; } } return QWidget::nativeEvent(eventType, message, result); }
在主程序中,還須要對該nativeEventFilter進行註冊才能生效:事件
UDisk *pDisk = new UDisk; qApp->installNativeEventFilter(pDisk);