參考網上資料,通過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編譯環境安裝與配置 http://www.linuxidc.com/Linux/2013-08/88539.htm
Linux系統下QT環境搭建 http://www.linuxidc.com/Linux/2013-07/87576.htm
Ubuntu下QT控制台程序無法運行的解決方案以及XTerm的配置方法 http://www.linuxidc.com/Linux/2013-06/86244.htm
Ubuntu 10.04下QT4.7.4移植詳解 http://www.linuxidc.com/Linux/2013-01/77930.htm
Ubuntu 14.04下安裝部署Qt5開發環境 http://www.linuxidc.com/Linux/2014-05/101774.htm
Qt 的詳細介紹:請點這裡
Qt 的下載地址:請點這裡