Qt提供了QAbstractNativeEventFilter来实现本地时间得过滤,通过对本地事件的检测,判断usb热插拔;(这里是windows 的例子);
首先,以QWidget, QAbstractNativeEventFilter为基类建立子类,重定义nativeEventFilter:
virtual bool nativeEventFilter(const QByteArray &eventType, void *message, long *result);
譬如:建立UDisk类, class UDisk : public QWidget, public QAbstractNativeEventFilter{}
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);