要做这个,要先知道Qt的QAbstractNativeEventFilter类,虚函数nativeEventFilter。这个类的主要作用是捕获全局windows消息。
先看一下效果:
基本注意以下两点:
1、新建的类要继承QAbstractNativeEventFilter
2、新建的类要被安装事件过滤,比如:
qApp->installNativeEventFilter(QAbstractNativeEventFilter *filterObj);
这里我封装了一个简单的类uDisk:
①头文件
#ifndef UDISK_H
#define UDISK_H
#include <QWidget>
#include <windows.h>
#include <QAbstractNativeEventFilter>
#include <dbt.h>
class uDisk : public QWidget, public QAbstractNativeEventFilter
{
Q_OBJECT
protected:
bool nativeEventFilter(const QByteArray &eventType, void *message, long *result);
signals:
void sigUDiskCome(QString uDiskName);
void sigUDiskRemove();
private:
char FirstDriveFromMask(ULONG unitmask);
};
#endif // UDISK_H
②源文件
#include "uDisk.h"
#include <QApplication>
#include <QDebug>
char uDisk::FirstDriveFromMask(ULONG unitmask)
{
char i;
for (i = 0; i < 26; ++i) {
if (unitmask & 0x1) {
break;
}
unitmask = unitmask >> 1;
}
return (i + 'A');
}
bool uDisk::nativeEventFilter(const QByteArray &eventType, void *message, long *result)
{
MSG* msg = reinterpret_cast<MSG*>(message);
int msgType = msg->message;
if(msgType == WM_DEVICECHANGE) {
PDEV_BROADCAST_HDR lpdb = (PDEV_BROADCAST_HDR)msg->lParam;
switch (msg->wParam) {
case DBT_DEVICEARRIVAL:
if(lpdb->dbch_devicetype == DBT_DEVTYP_VOLUME) {
PDEV_BROADCAST_VOLUME lpdbv = (PDEV_BROADCAST_VOLUME)lpdb;
if(lpdbv->dbcv_flags ==0) {
QString USBDisk = QString(this->FirstDriveFromMask(lpdbv ->dbcv_unitmask));
emit sigUDiskCome(USBDisk);
}
}
break;
case DBT_DEVICEREMOVECOMPLETE:
if(lpdb->dbch_devicetype == DBT_DEVTYP_VOLUME) {
PDEV_BROADCAST_VOLUME lpdbv = (PDEV_BROADCAST_VOLUME)lpdb;
if(lpdbv->dbcv_flags == 0) {
emit sigUDiskRemove();
}
}
break;
case DBT_DEVNODES_CHANGED:
break;
default:
break;
}
}
return QWidget::nativeEvent(eventType, message, result);
}
如何使用:
1、引用头文件#include "uDisk.h"
2、声明uDisk *m_uDisk = Q_NULLPTR;
3、调用:
m_uDisk = new uDisk;
qApp->installNativeEventFilter(m_uDisk);
connect(m_uDisk, &uDisk::sigUDiskCome, [=](QString uDiskName){
ui->label->setText(tr("U Disk Come!").append(tr("The Disk is ") + uDiskName));
});
connect(m_uDisk, &uDisk::sigUDiskRemove, [=](){
ui->label->setText(tr("U Disk Remove!"));
});
4、在调用类析构时记得析构掉:
if(m_uDisk) {
delete m_uDisk;
m_uDisk = Q_NULLPTR;
}