Qt:监控设备插入拔除

nativeEvent里面解析系统消息,获取USB等设备的插入和拔出事件。

使用步骤:

  1. 窗口初始化时使用RegisterDeviceNotification注册设备通知

  2. nativeEvent函数里面解析系统消息

  3. 窗口关闭时,使用UnregisterDeviceNotification关闭指定的设备通知句柄

关键代码如下:

  • 注册设备通知
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) {
    ui->setupUi(this);

    DEV_BROADCAST_DEVICEINTERFACE notificationFilter;
    ZeroMemory(¬ificationFilter, sizeof(notificationFilter));
    notificationFilter.dbcc_size = sizeof(DEV_BROADCAST_DEVICEINTERFACE);
    notificationFilter.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE;
    notificationFilter.dbcc_classguid = GUID_DEVINTERFACE_USB_DEVICE;
    devNotify = RegisterDeviceNotification(reinterpret_cast(this->winId()), ¬ificationFilter, DEVICE_NOTIFY_WINDOW_HANDLE);// DEVICE_NOTIFY_WINDOW_HANDLE); DEVICE_NOTIFY_ALL_INTERFACE_CLASSES
    if (!devNotify) {
        qWarning() << "RegisterDeviceNotification failed";
    }
}
  • 解析系统消息
bool MainWindow::nativeEvent(const QByteArray &eventType, void *message, qintptr *result) {
    MSG *msg = (MSG *) message;
    if (msg->message == WM_DEVICECHANGE) {
        auto hdr = reinterpret_cast(msg->lParam);
        switch (msg->wParam) {
            case DBT_DEVICEARRIVAL:
                if (hdr->dbch_devicetype == DBT_DEVTYP_DEVICEINTERFACE) {
                    auto info = (PDEV_BROADCAST_DEVICEINTERFACE) hdr;
                    auto devName = QString::fromWCharArray(info->dbcc_name);
                    qDebug() << "+: " << devName;
                }
                break;
            case DBT_DEVICEREMOVECOMPLETE:
                if (hdr->dbch_devicetype == DBT_DEVTYP_DEVICEINTERFACE) {
                    auto info = (PDEV_BROADCAST_DEVICEINTERFACE) hdr;
                    auto devName = QString::fromWCharArray(info->dbcc_name);
                    qDebug() << "-: " << devName;
                }
                break;
        }
    }
    return false;
}

插拔串口时,输出如下:

+:  "\\\\?\\USB#VID_1A86&PID_7523................................."
-:  "\\\\?\\USB#VID_1A86&PID_7523................................."
  • 关闭指定的设备通知句柄
MainWindow::~MainWindow() {
    if (devNotify) {
        UnregisterDeviceNotification(devNotify);
    }
}

版权声明:本文为「txfly」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://www.jianshu.com/p/9ec8a56c3f0f

你可能感兴趣的:(Qt:监控设备插入拔除)