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

#include 
#include 

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(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: "< 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');
}

 

 

你可能感兴趣的:(QT)