小程序代码:https://github.com/markmark999/Hellow-World/tree/master/wintest
看了网上很多关于注册热键的帖子,自己动手写了一个。
一共三步:
1在构造函数中注册热键
2继承QAbstractNativeEventFilter类重写虚函数nativeEventFilter响应系统消息
3在析构函数中注销热键
先创建一个Mainwindow或Widget的Qt程序,然后在头文件的类上添加父类QAbstractNativeEventFilter,声明函数nativeEventFilter
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include<QAbstractNativeEventFilter>
#include <QMainWindow>
#include<windows.h>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow,public QAbstractNativeEventFilter
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
virtual bool nativeEventFilter(const QByteArray &eventType, void *msg, long *) Q_DECL_OVERRIDE;
private:
Ui::MainWindow *ui;
ATOM atom;
};
#endif // MAINWINDOW_H
在构造函数中注册热键我这里热键辅键为alt,热键为F8.开启监听,GlobalAddAtom函数可能会报错,因为字符格式不同。在.pro文件里添加 DEFINES-= UNICODE 即可解决。
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
atom=GlobalAddAtom("a");
BOOL a=RegisterHotKey((HWND)winId(),atom,MOD_ALT,VK_F8);
if(a)
qApp->installNativeEventFilter(this);
}
析构函数中别忘了注销
MainWindow::~MainWindow()
{
delete ui;
BOOL b=UnregisterHotKey((HWND)winId(),atom);
GlobalDeleteAtom(atom);
}
定义响应函数接收windows系统消息,其实是个事件过滤器。
bool MainWindow::nativeEventFilter(const QByteArray &eventType, void *msg, long *)
{
if(eventType=="windows_generic_MSG")
{
MSG *pmsg=reinterpret_cast<MSG*>(msg);
if((WM_HOTKEY==pmsg->message)&&((UINT)LOWORD(pmsg->lParam)==MOD_ALT)&&((UINT)HIWORD(pmsg->lParam)==VK_F8)){
if(this->isHidden())
this->show();
else
this->hide();
return true;
}
return false;
}
return false;
}
热键注册,事件过滤器这些细节有时间再补上。
演示视频(热键为alt+F8)
下面是我参考的帖子链接:
https://blog.csdn.net/luoshabugui/article/details/82428500
https://blog.csdn.net/zhangjinqing1234/article/details/49903613