工作中,需要检测u盘的插入和拔掉。其余逻辑可以简化。
查了半天,感谢@q62290798
链接在
https://blog.csdn.net/q62290798/article/details/115869367?utm_medium=distribute.pc_relevant.none-task-blog-2defaultbaidujs_baidulandingword~default-1-115869367-blog-100083606.pc_relevant_3mothn_strategy_and_data_recovery&spm=1001.2101.3001.4242.2&utm_relevant_index=4
总结下
1,派生自QAbstractNativeEventFilter类
2,重写nativeEventFilter,通过WM_DEVICECHANGE,DBT_DEVICEARRIVAL,DBT_DEVICEREMOVECOMPLETE判断是否u盘插入和拔出。
3,在main()函数注册
废话不多说,贴代码如下
#pragma once
#include <QtWidgets/QMainWindow>
#include “ui_USBDisck.h”
#include
#include <Windows.h>
#include <Dbt.h>
#include <qdir.h>
#include <qdesktopwidget.h>
#include <qprocess.h>
#include <qcheckbox.h>
#include <qabstractnativeeventfilter.h>
class USBDisck : public QMainWindow, public QAbstractNativeEventFilter
{
Q_OBJECT
public:
USBDisck(QWidget *parent = Q_NULLPTR);
private:
Ui::USBDisckClass ui;
private:
bool nativeEventFilter(const QByteArray &eventType, void *message, long *result);
};
#include “USBDisck.h”
#include
#include <QtCore/QCoreapplication.h>
USBDisck::USBDisck(QWidget *parent)
-
QMainWindow(parent)
{
ui.setupUi(this);
}
bool USBDisck::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:
{
qDebug() << “usb arrived!”;
}
break;
case DBT_DEVICEREMOVECOMPLETE:
{
qDebug() << "Remove usb";
}
break;
default:
break;
}
}
return false;
}
#include “USBDisck.h”
#include <QtWidgets/QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
USBDisck w;
w.show();
a.installNativeEventFilter(&w);
return a.exec();
}