PDA

View Full Version : QAbstractNativeEventFilter::nativeEventFilter not receiving DBT_DEVICEARRIVAL



bhavyasg
10th May 2016, 09:02
Hi All,

I am trying to get a USb insertion and removal event in a non-GUI class but with much success. I am not able to get the arrival and removal events. Can anyone lend some pointers. My code looks like -


Usbdetection.h
============



#ifndef USBDETECTION_H
#define USBDETECTION_H

#include <QAbstractNativeEventFilter>
#include <QProcess>
#include <QMap>

class UsbDetection : public QAbstractNativeEventFilter
{

public:
UsbDetection();
virtual bool nativeEventFilter(const QByteArray &eventType, void *message, long *) Q_DECL_OVERRIDE;
};


#endif // USBDETECTION_H



UsbDetection.cpp
=============


#include <QByteArray>
#include <windows.h>
#include <dbt.h>
#include "UsbDetection.h"
#include <QDebug>
#include <QDir>

UsbDetection::UsbDetection()
: QAbstractNativeEventFilter()
/*, mWmicProcess(new QProcess())
, mIsDevInsertion(FALSE)
, mDriveToDevNameMap(new QMap<QString, TDriveToMediaPair>())*/
{
qDebug() << "In constructor()";
}

bool UsbDetection::nativeEventFilter(const QByteArray &eventType, void *pMessage, long* pResult) //Q_DECL_OVERRIDE
{
qDebug() << " In native events" ;
Q_UNUSED(eventType);
Q_UNUSED(pResult);

auto pWindowsMessage = static_cast<MSG*>(pMessage);
auto wParam = pWindowsMessage->wParam;
qDebug() << "wParam = " << wParam;

if (wParam == DBT_DEVICEARRIVAL || wParam == DBT_DEVICEREMOVECOMPLETE) {
qDebug() << "USB plug/unplug = " << wParam;
....................

}
return true;
}


main.cpp
========


#include <QApplication>

#include <QDebug>
#include <QDir>
#include <QAbstractEventDispatcher>

#include "UsbDetection.h"

int main(int argc, char *argv[])
{
QCoreApplication app(argc, argv);

UsbDetection UsbDetection;
app.installNativeEventFilter(&UsbDetection);
return app.exec();
}



Output :
=======
In constructor()
In native events
wParam = 0
In native events
wParam = 0
In native events
wParam = 0
In native events
wParam = 0

anda_skoa
10th May 2016, 12:43
Are you sure your application will work at all with you filtering away all native events?

Cheers,
_

bhavyasg
10th May 2016, 13:21
This app is required just to put divide USB events. I am not directing anything else from the app. Is that what you wanted to know?

anda_skoa
10th May 2016, 14:03
What i mean is: you are obviously getting native events but you filter them out.
Are you sure the base implementation in QCoreApplication doesn't need them?

Cheers,
_

bhavyasg
11th May 2016, 09:50
if you are talking about the return value from nativeEvent, then I have tried with false. But I still don't get the usb insertion/removal events

anda_skoa
13th May 2016, 09:30
Hmm, then maybe it is necessary to register for these events by calling some Windows API?

Also maybe check if libusb can deliver those notifications or if using a Qt hardware managemenSolid (https://inqlude.org/libraries/solid.html) is a workable option.

Cheers,
_