Qt注册热键打开窗口

小程序代码: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://b23.tv/Nj400Z

下面是我参考的帖子链接:

https://blog.csdn.net/luoshabugui/article/details/82428500

https://blog.csdn.net/zhangjinqing1234/article/details/49903613

https://www.cnblogs.com/lvdongjie/p/3944204.html

http://blog.sina.com.cn/s/blog_825ad93f0102xywl.html

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值