windows下鼠标键盘热插拔监测(Qt)
1、实现方式
2、源码地址
3、适用系统
4、实现效果
5、实现代码
#ifndef MOUSEKEYTEST_H
#define MOUSEKEYTEST_H
#include <QWidget>
namespace Ui {
class MouseKeyTest;
}
class MouseKeyTest : public QWidget
{
Q_OBJECT
public:
explicit MouseKeyTest(QWidget *parent = nullptr);
~MouseKeyTest();
private:
bool nativeEvent(const QByteArray &eventType, void *message, long *result);
void registerGUID();
private:
Ui::MouseKeyTest *ui;
};
#endif
#include "mousekeytest.h"
#include "ui_mousekeytest.h"
#include <qdebug.h>
#include <windows.h>
#include "dbt.h"
#include "initguid.h"
#include "usbiodef.h"
#include "hidclass.h"
#include "ntddkbd.h"
#include "ntddmou.h"
MouseKeyTest::MouseKeyTest(QWidget *parent) :
QWidget(parent),
ui(new Ui::MouseKeyTest)
{
ui->setupUi(this);
this->setWindowTitle("鼠标、键盘热插拔监测。");
registerGUID();
}
MouseKeyTest::~MouseKeyTest()
{
delete ui;
}
void MouseKeyTest::registerGUID()
{
DEV_BROADCAST_DEVICEINTERFACE mouseInterface;
ZeroMemory(&mouseInterface, sizeof(DEV_BROADCAST_DEVICEINTERFACE));
mouseInterface.dbcc_size = sizeof(DEV_BROADCAST_DEVICEINTERFACE);
mouseInterface.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE;
mouseInterface.dbcc_classguid = GUID_DEVINTERFACE_MOUSE ;
if(!RegisterDeviceNotificationW((HANDLE)this->winId(), &mouseInterface, DEVICE_NOTIFY_WINDOW_HANDLE))
{
qDebug() << "鼠标GUID注册失败";
}
DEV_BROADCAST_DEVICEINTERFACE keyboardInterface;
ZeroMemory(&keyboardInterface, sizeof(DEV_BROADCAST_DEVICEINTERFACE));
keyboardInterface.dbcc_size = sizeof(DEV_BROADCAST_DEVICEINTERFACE);
keyboardInterface.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE;
keyboardInterface.dbcc_classguid = GUID_DEVINTERFACE_KEYBOARD;
if(!RegisterDeviceNotificationW((HANDLE)this->winId(), &keyboardInterface, DEVICE_NOTIFY_WINDOW_HANDLE))
{
qDebug() << "键盘GUID注册失败";
}
}
bool MouseKeyTest::nativeEvent(const QByteArray &eventType, void *message, long *result)
{
MSG* msg = reinterpret_cast<MSG*>(message);
if(msg->message == WM_DEVICECHANGE)
{
PDEV_BROADCAST_HDR lpdb = (PDEV_BROADCAST_HDR)msg->lParam;
PDEV_BROADCAST_DEVICEINTERFACE lpdbv = (PDEV_BROADCAST_DEVICEINTERFACE)lpdb;
switch (msg->wParam)
{
case DBT_DEVICEARRIVAL:
{
if(lpdb->dbch_devicetype == DBT_DEVTYP_DEVICEINTERFACE)
{
if(lpdbv->dbcc_classguid == GUID_DEVINTERFACE_KEYBOARD)
{
ui->textEdit->append("键盘插入:" + QString::fromWCharArray(lpdbv->dbcc_name));
}
else if(lpdbv->dbcc_classguid == GUID_DEVINTERFACE_MOUSE)
{
ui->textEdit->append("鼠标插入:" + QString::fromWCharArray(lpdbv->dbcc_name));
}
}
break;
}
case DBT_DEVICEREMOVECOMPLETE:
{
if(lpdb->dbch_devicetype == DBT_DEVTYP_DEVICEINTERFACE)
{
if(lpdbv->dbcc_classguid == GUID_DEVINTERFACE_KEYBOARD)
{
ui->textEdit->append("键盘移除:" + QString::fromWCharArray(lpdbv->dbcc_name));
}
else if(lpdbv->dbcc_classguid == GUID_DEVINTERFACE_MOUSE)
{
ui->textEdit->append("鼠标移除:" + QString::fromWCharArray(lpdbv->dbcc_name));
}
}
break;
}
default:
break;
}
}
return false;
}