qt 注册热键

  1. 将所需的库添加到您的qmake项目(.PRO文件)
LIBS += \
    -lUser32

2.在代码中包含所需的头文件。

#include <windows.h>
  1. 在程序开始时注册热键
// 热键id
#define HOT_KEY_ALT_CTRL_M 0
#define HOT_KEY_CTRL_A 1

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    // ALT + CTRL + M
    if (!RegisterHotKey(HWND(winId()), HOT_KEY_ALT_CTRL_M, MOD_ALT | MOD_CONTROL, 0x4D))
    {
        qDebug() << "注册热键 ALT + CTRL + M ok.";
    }

    // CTRL + A
    if (!RegisterHotKey(HWND(winId()), HOT_KEY_CTRL_A, MOD_CONTROL, 0x41))
    {
        qDebug() << "注册热键  CTRL + A ok.";
    }
}
  1. 重写MainWindow应用程序中的nativeEvent函数

先申明

bool nativeEvent(const QByteArray &eventType, void *message, long *result);

在实现

bool MainWindow::nativeEvent(const QByteArray &eventType, void *message, long *result)
{
    Q_UNUSED(eventType);
    Q_UNUSED(result);
    MSG* msg = static_cast<MSG*>(message);
    if (msg->message == WM_HOTKEY)
    {
        switch (msg->wParam) {
        case HOT_KEY_ALT_CTRL_M:
            qDebug() << "触发了: ALT + CTRL + M";
            break;
        case HOT_KEY_CTRL_A:
            qDebug() << "触发了: CTRL + A";
            break;
        default:
            qDebug() << "被注入了其他热键.";
        }
        return true;
    }
    return false;
}

ok...

posted @ 2020-05-08 08:18  Ajanuw  阅读(839)  评论(0编辑  收藏  举报