Detected a new USB device connected / disconnected on Qt

advertisements

I want to be notified when a new usb device is connected or disconnected (device hid). I have succeeded to be notified when there is a usb device change but I don't know if the device is connected or disconnected. The message I receive (when usb attached or detached) is the same : message : 537 (VM_DEVICECHANGE) wParam : 7 lParam : 0

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QAbstractEventDispatcher>
#include <QAbstractNativeEventFilter>
#include <QDebug>
#include <windows.h>
#include <dbt.h>
#include <QObject>

class MyNativeEventFilter : public QAbstractNativeEventFilter {
public :
    virtual bool nativeEventFilter( const QByteArray &eventType, void *message, long *result )
    Q_DECL_OVERRIDE
    {
        if (eventType == "windows_generic_MSG")
        {
          MSG *msg = static_cast<MSG *>(message);
          static int i = 0;

              msg = (MSG*)message;
                  qDebug() << "message: " << msg->message << " wParam: " << msg->wParam
                      << " lParam: " << msg->lParam;
              if (msg->message == WM_DEVICECHANGE)
              {
                  qDebug() << "WM_DEVICECHANGE";
              }
            }
        return false;
    }
};

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);
    MyNativeEventFilter myEventfilter;
    app.eventDispatcher()->installNativeEventFilter(&myEventfilter);
    QQmlApplicationEngine engine;
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));

    return app.exec();
}


The WM_DEVICECHANGE message doesn't really tell you whether a device was connected or disconnected. After receiving that message, your application should use SetupAPI to look at all the USB devices that are connected and take an appropriate action.