C++ Qt 识别U盘/串口
头文件:
#include <Windows.h> // 包含 Windows API 头文件
#include <Dbt.h> // 包含设备通知相关的头文件
识别U盘:
//.h
bool nativeEvent(const QByteArray &eventType,
void *message,
long *result) override;
bool nativeEvent(const QByteArray &eventType,
void *message,
long *result)
{
Q_UNUSED(eventType)
MSG* msg = (MSG*)message;
if (msg->message == WM_DEVICECHANGE)
{
if (msg->wParam == DBT_DEVICEARRIVAL)
{
PDEV_BROADCAST_HDR devHdr = (PDEV_BROADCAST_HDR)msg->lParam;
if (devHdr->dbch_devicetype == DBT_DEVTYP_VOLUME)
{
//U盘插入, 更新驱动器列表
}
*result = 0;
}
else if (msg->wParam == DBT_DEVICEREMOVECOMPLETE)
{
PDEV_BROADCAST_HDR devHdr = (PDEV_BROADCAST_HDR)msg->lParam;
if (devHdr->dbch_devicetype == DBT_DEVTYP_VOLUME)
{
//U盘拔出, 更新驱动器列表
}
*result = 0;
}
}
return false;//返回false表明该消息接着向下传递,以便其它应用处理该消息。
}
识别虚拟串口:
//.h
bool handleVirtualSerialPortEvent(MSG* msg, long* result);
bool nativeEvent(const QByteArray &eventType,
void *message,
long *result) override;
bool handleVirtualSerialPortEvent(MSG* msg, long* result)
{
if (msg->message == WM_DEVICECHANGE)
{
if (msg->wParam == DBT_DEVICEARRIVAL)
{
PDEV_BROADCAST_HDR devHdr = (PDEV_BROADCAST_HDR)msg->lParam;
if (devHdr->dbch_devicetype == DBT_DEVTYP_PORT)
{
// 处理虚拟串口插入事件
}
*result = 0;
}
else if (msg->wParam == DBT_DEVICEREMOVECOMPLETE)
{
PDEV_BROADCAST_HDR devHdr = (PDEV_BROADCAST_HDR)msg->lParam;
if (devHdr->dbch_devicetype == DBT_DEVTYP_PORT)
{
// 处理虚拟串口拔出事件
}
*result = 0;
}
else if (msg->wParam == DBT_DEVNODES_CHANGED)
{
// 处理虚拟串口节点变化事件,如果串口连接,可能会不触发拔出事件
*result = 0;
}
}
return false;
}
bool nativeEvent(const QByteArray &eventType, void *message, long *result)
{
Q_UNUSED(eventType)
MSG* msg = (MSG*)message;
return handleVirtualSerialPortEvent(msg, result);
}
获取更多Linux C/C++资料