pro文件添加:
QT += core gui serialport
MainWindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
private slots:
void slots_USBInsertionMessage(); //USB插入消息
void slots_USBUnplugMessage(); //USB拔出消息
private slots:
void on_pushButton_clicked();
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
mainwindow.cpp添加:
usb_listener *m_usb_listener = Q_NULLPTR;
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
m_usb_listener = new usb_listener;
qApp->installNativeEventFilter(m_usb_listener);
connect(m_usb_listener, SIGNAL(signals_DevicePlugIn()), this, SLOT(slots_USBInsertionMessage()));
connect(m_usb_listener, SIGNAL(signals_DevicePlugOut()), this, SLOT(slots_USBUnplugMessage()));
}
void MainWindow::slots_USBInsertionMessage()
{
qDebug()<< QString::fromLocal8Bit("USB 插入 回调");
}
void MainWindow::slots_USBUnplugMessage()
{
qDebug()<< QString::fromLocal8Bit("USB 拔出 回调");
}
USB监听类:
usb_listener.h
#ifndef USB_LISTENER_H
#define USB_LISTENER_H
#include <QWidget>
#include <windows.h>
#include <QAbstractNativeEventFilter>
#include <dbt.h>
class usb_listener:public QWidget, public QAbstractNativeEventFilter
{
Q_OBJECT
public:
void EmitMySignal();
protected:
bool nativeEventFilter(const QByteArray &eventType, void *message, long *result);
signals:
// void signals_DeviceChangeCbk();
void signals_DevicePlugIn();
void signals_DevicePlugOut();
};
#endif // USB_LISTENER_H
usb_listener.cpp
#include "usb_listener.h"
#include <QApplication>
#include <QDebug>
bool usb_listener::nativeEventFilter(const QByteArray &eventType, void *message, long *result)
{
MSG* msg = reinterpret_cast<MSG*>(message);
unsigned int msgType = msg->message;
if(msgType == WM_DEVICECHANGE) {
// emit signals_DeviceChangeCbk();
if(msg->wParam == DBT_DEVICEARRIVAL)
{
qDebug("usb in");
emit signals_DevicePlugIn(); //触发信号
}
if(msg->wParam == DBT_DEVICEREMOVECOMPLETE)
{
qDebug("usb out");
emit signals_DevicePlugOut(); //触发信号
}
}
return QWidget::nativeEvent(eventType, message, result);
}
//触发信号 测试
void usb_listener::EmitMySignal()
{
emit signals_DevicePlugIn();
}