首页 > 代码库 > QT 监听 USB 设备 插入、拔出动作
QT 监听 USB 设备 插入、拔出动作
参考网上资料,通过QT 实现
#ifndef WIDGET_H #define WIDGET_H #include <QtGui/QWidget> #include <windows.h> #include <QString> class Widget : public QWidget { Q_OBJECT public: Widget(QWidget *parent = 0); ~Widget(); protected: bool winEvent(MSG *msg, long *result); private: //UsbConfig usbConfig; char FirstDriveFromMask (ULONG unitmask); }; #endif // WIDGET_H
#include "qt_Watch/qwidget.h" #include <QDebug> #include <Windows.h> #include <dbt.h> Widget::Widget(QWidget *parent) : QWidget(parent) { setWindowFlags(Qt::Window); //窗口以Window为父窗口 } Widget::~Widget() { } bool Widget::winEvent(MSG *msg,long *result) { int msgType = msg->message; if(msgType == WM_DEVICECHANGE) { qDebug() << "收到事件 " ; PDEV_BROADCAST_HDR lpdb = (PDEV_BROADCAST_HDR)msg->lParam; switch(msg->wParam) { case DBT_DEVICETYPESPECIFIC: { qDebug() << "DBT_DEVICETYPESPECIFIC " ; break; } case DBT_DEVICEARRIVAL: if (lpdb -> dbch_devicetype == DBT_DEVTYP_VOLUME) { PDEV_BROADCAST_VOLUME lpdbv = (PDEV_BROADCAST_VOLUME)lpdb; if (lpdbv -> dbcv_flags == 0) { // 插入U盘,此处可以做你想做的事 QString USBDisk = QString(this->FirstDriveFromMask(lpdbv ->dbcv_unitmask)); qDebug() << "USB_Arrived and The USBDisk is: "<<USBDisk ; } } qDebug() << "DBT_DEVICEARRIVAL" ; break; case DBT_DEVICEREMOVECOMPLETE: if (lpdb -> dbch_devicetype == DBT_DEVTYP_VOLUME) { PDEV_BROADCAST_VOLUME lpdbv = (PDEV_BROADCAST_VOLUME)lpdb; if (lpdbv -> dbcv_flags == 0) { qDebug() << "USB_设备移除"; } } qDebug() << "DBT_DEVICEREMOVECOMPLETE" ; break; } } return false; } char Widget::FirstDriveFromMask (ULONG unitmask) { char i; for (i = 0; i < 26; ++i) { if (unitmask & 0x1) break; unitmask = unitmask >> 1; } return (i + ‘A‘); }
#include <QApplication> #include "qt_Watch/qwidget.h" int main(int argc,char ** argv) { QApplication app(argc,argv); Widget widget; widget.show(); return app.exec(); }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。