Qt Windows上USB设备热插拔检测 可用于USB转串口的实时监测

#include <dbt.h>
#include <windows.h>

private:
	//UsbConfig usbConfig;
	char FirstDriveFromMask(ULONG unitmask);

protected:
	bool nativeEvent(const QByteArray &eventType, void *message, long *result);




bool nativeEvent(const QByteArray &eventType, void *message, long *result)
{
	Q_UNUSED(eventType);
	MSG* msg = reinterpret_cast<MSG*>(message);
	int msgType = msg->message;
	printf("msgType:%x\r\n" , msgType);
	if (msgType == WM_DEVICECHANGE) {
		qDebug() << "Recv Event ";	
                //读取串口信息  
		foreach(const QSerialPortInfo &info, QSerialPortInfo::availablePorts())
		{

                }
		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盘,此处可以做你想做的事 
						// lpdbv->dbcv_unitmask 
                                                //即盘符标志位,1bit,0为A,1为B,10为C,11为D…以此类推 
						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_delete"; 
					} 
				} 
				qDebug() << "DBT_DEVICEREMOVECOMPLETE" ;
				break; 
		} 
	}
	return false; 
} 


char FirstDriveFromMask(ULONG unitmask)
{ 
	char i; 
	for (i = 0; i < 26; ++i)
	{
		if (unitmask & 0x1)
			break;
		unitmask = unitmask >> 1;
	}
	return (i + 'A');
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值