参考网上资料,通过QT 实现监听 USB 设备 插入、拔出动作
#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();
}
Ubuntu 环境下Gtk与QT编译环境安装与配置