码迷,mamicode.com
首页 > 其他好文 > 详细

QT 监听 USB 设备 插入、拔出动作

时间:2014-07-13 16:53:33      阅读:187      评论:0      收藏:0      [点我收藏+]

标签:for   io   re   window   type   amp   

参考网上资料,通过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();
}


QT 监听 USB 设备 插入、拔出动作,布布扣,bubuko.com

QT 监听 USB 设备 插入、拔出动作

标签:for   io   re   window   type   amp   

原文地址:http://blog.csdn.net/zhuyingqingfen/article/details/37726981

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!