Windows下Qt检测移动U盘及动态插拔

windows下提供了很便捷的方式查找和动态监测U盘的插拔。windows sdk里面提供了对应api。从所有的事件中处理对应的事件即可。

Device Management Events

1.U盘已插入电脑的情况下。使用QDir获取所有驱动,再通过驱动类型判断和查找移动U盘。以下为关键代码段

    QFileInfoList infoList = QDir::drives();
    foreach(const QFileInfo& info, infoList)
    {
        QString path = info.filePath();
        UINT iRes = ::GetDriveType((WCHAR *)path.toStdWString().c_str());
        if (DRIVE_REMOVABLE == iRes)
        {
            qDebug() << path;
        }
    }

 

2.通过QAbstractNativeEventFilter,或nativeEvent方法来监测U盘的接入或拔出。


        PDEV_BROADCAST_HDR lpdbh = (PDEV_BROADCAST_HDR)msg->lParam;
        switch (msg->wParam)
        {
        case DBT_DEVICEARRIVAL:
        case DBT_DEVICEREMOVECOMPLETE:
            if (lpdbh->dbch_devicetype == DBT_DEVTYP_VOLUME)
            {
                PDEV_BROADCAST_VOLUME lpdbv = (PDEV_BROADCAST_VOLUME)lpdbh;
                //0:uDisk etc.  1.cd driver
                if (lpdbv->dbcv_flags == 0)
                {
                    //....
                }
            }
            break;
        }

参考链接:

https://docs.microsoft.com/en-us/windows/win32/devio/device-management-events

你可能感兴趣的:(Qt)