Qt WinAPI - Lesson 005. Global HotKey WinAPI in Qt5

Qt, HotKey, RegisterHotKey, UnregisterHotKey, WinAPI, горячие клавиши

To work with global HotKey in Qt5 , there is a virtual method nativeEvent . This method replaces the methods winEvent , x11Event , macEvent of Qt 4.8 .

The especiality in the HotKey to Qt is that if the window is not in focus, that is, it is, for example, will be minimized to the system tray, then registered QShortcut simply will not work. It is therefore necessary to work with the global events from the operating system, that is, go to the realization of the platform-specific code in the application to Qt.


In this example Let us examine the option of working with WinAPI. For this we use the function RegisterHotKey.

BOOL WINAPI RegisterHotKey(
  _In_opt_ HWND hWnd,
  _In_     int  id,
  _In_     UINT fsModifiers,
  _In_     UINT vk

RegisterHotKey parameters

hWnd [in, optional]

A handle to the window that will receive WM_HOTKEY messages generated by the hot key. If this parameter is NULL , WM_HOTKEY messages are posted to the message queue of the calling thread and must be processed in the message loop.

id [in]

Type: int
The identifier of the hot key. If the hWnd parameter is NULL, then the hot key is associated with the current thread rather than with a particular window. If a hot key already exists with the same hWnd and id parameters, see Remarks for the action taken.

fsModifiers [in]

Type: UINT The keys that must be pressed in combination with the key specified by the uVirtKey parameter in order to generate the WM_HOTKEY message. The fsModifiers parameter can be a combination of the following values.

  • MOD_ALT 0x0001 - Either ALT key must be held down.
  • MOD_CONTROL 0x0002 - Either CTRL key must be held down.
  • MOD_NOREPEAT 0x4000 - Changes the hotkey behavior so that the keyboard auto-repeat does not yield multiple hotkey notifications. Windows Vista: This flag is not supported.
  • MOD_SHIFT 0x0004 - Either SHIFT key must be held down.
  • MOD_WIN 0x0008 - Either WINDOWS key was held down. These keys are labeled with the Windows logo. Keyboard shortcuts that involve the WINDOWS key are reserved for use by the operating system.

vk [in]

Type: UINT
The virtual-key code of the hot key.


Disable keyboard shortcuts.

BOOL WINAPI UnregisterHotKey(
  _In_opt_ HWND hWnd,
  _In_     int  id

UnregisterHotKey Parameters

hWnd [in, optional]

Type: HWND
A handle to the window associated with the hot key to be freed. This parameter should be NULL if the hot key is not associated with a window.

id [in]

Type: int
The identifier of the hot key to be freed.

An example of a HotKey in WinAPI

Create a project to work with HotKey. This project will be present QSystemTrayIcon object class. Let's hide the application in the system tray and check hotkeys. That combination is "ALT + SHIFT + D", for example. In this project, the handler hotkeys will MainWindow. Treatment of combinations of hot keys will be made in nativeEvent.

Check on the selected combination of hot keys will produce via qDebug().



#include <QMainWindow>
#include <QSystemTrayIcon>
#include "windows.h" // Connect WinAPI library

namespace Ui {
class MainWindow;

class MainWindow : public QMainWindow

    explicit MainWindow(QWidget *parent = 0);

    // The method for processing native events from the OS in Qt
    bool nativeEvent(const QByteArray &eventType, void *message, long *result);

private slots:
    void iconActivated(QSystemTrayIcon::ActivationReason reason);

    Ui::MainWindow *ui;
    QSystemTrayIcon *trayIcon;

#endif // MAINWINDOW_H


#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>

MainWindow::MainWindow(QWidget *parent) :
    ui(new Ui::MainWindow)
    /* System Tray Icon is necessary to the application window is not in focus
     * */
    trayIcon = new QSystemTrayIcon(this);

    connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
            this, SLOT(iconActivated(QSystemTrayIcon::ActivationReason)));

    // Register HotKey "ALT+SHIFT+D"
    RegisterHotKey((HWND)MainWindow::winId(),   // Set the system identifier of the widget window that will handle the HotKey
                   100,                         // Set identifier HotKey
                   MOD_ALT | MOD_SHIFT,         // Set modifiers
                   'D');                        // We define hotkeys for HotKey

    delete ui;

bool MainWindow::nativeEvent(const QByteArray &eventType, void *message, long *result)
    // Transform the message pointer to the MSG WinAPI
    MSG* msg = reinterpret_cast<MSG*>(message);

    // If the message is a HotKey, then ...
    if(msg->message == WM_HOTKEY){
        // ... check HotKey
        if(msg->wParam == 100){
            // We inform about this to the console
            qDebug() << "HotKey worked";
            return true;
    return false;

void MainWindow::iconActivated(QSystemTrayIcon::ActivationReason reason)
    switch (reason){
    case QSystemTrayIcon::Trigger:
        !isVisible() ? show() : hide();


To ensure that the project is compiled with MSVC build a set, add the following lines to pro project file:

    LIBS += -luser32


As a result of this processing will code the global keyboard shortcuts, even if the application window will be hidden in the system tray tray.


10% refund of hotel reservation amount on Booking
10% refund of hotel reservation amount on Booking
We offer a link with a 10% return on the amount of the order when booking a hotel through Booking
Support the author Donate


Only authorized users can post comments.
Please, Log in or Sign up
Looking for a Job?
14,000.00 руб. - 40,000.00 руб.
Разработчик Qt
Annino, Moscow Oblast, Russia
5,000.00 руб. - 15,000.00 руб.
Moskovskiy, Moscow, Russia
25,000.00 руб. - 30,000.00 руб.
Разработчик Qt/C++
Barnaul, Altai Krai, Russia

For registered users on the site there is a minimum amount of advertising

Aug. 22, 2019, 11:24 p.m.

Qt - Test 001. Signals and slots

  • Result:47points,
  • Rating points-6
Aug. 21, 2019, 10:23 a.m.
Andrej Ermoshin

C++ - Test 002. Constants

  • Result:58points,
  • Rating points-2
Aug. 21, 2019, 10:15 a.m.
Andrej Ermoshin

C++ - Test 001. The first program and data types

  • Result:86points,
  • Rating points6
Last comments
Aug. 19, 2019, 7:41 a.m.
Andrej Jankovich

это проблема дистрибутива, попробуйте установить через пакетный менеджер snap Суть проблемы: libQt5Core которая лежит в дистрибутиве требует версию glibc >= 2.25 у вас видимо …
Aug. 18, 2019, 6:09 a.m.

cqtdeployer /home/aleks/CQtDeployer/bin/cqtdeployer: /lib/x86_64-linux-gnu/libc.so.6: version `GLIBC_2.25' not found (required by /home/aleks/CQtDeployer/lib/libQt5Core.so.5) linux mint …
Aug. 17, 2019, 9:04 a.m.

github ChekableTView Правой групповая смена значения при перетаскивании левой как обычно.
Aug. 16, 2019, 1:03 p.m.
Evgenij Legotskoj

Потому, что в минуте 60 секунд
Aug. 16, 2019, 12:16 p.m.

а почему делитель 60000, а не 1000?
Now discuss on the forum
Aug. 24, 2019, 7:21 a.m.
Evgenij Legotskoj

Не помню, давно уже с QML не работал, по-моему, обычно пишет в консоль, что не находит файл. В любом случае какую-то ошибку в консоль выкидывает. Но если честно, если у вас проект будет ак…
Aug. 24, 2019, 4:27 a.m.
Brjus Gliff

Спасибо, вначале в документации было не понятно что к чему, теперь разобрался
Aug. 21, 2019, 8:36 a.m.

Александр, мне не нужно перебирать. Вы говорите правильно, сначала я написал избыточный код просто не подумав. Задача такая, мне нужно просто переложить из QMap в атрибуты xml тега все, что там …
Aug. 21, 2019, 3:16 a.m.

Если Вы разрабатываете какую-то универсальную утилиту, которая вообще не привязана к логике, тогда как вариант: 1. Получить список таблиц через QSqlDatabase::tables 2. Для каждой табли…
© EVILEG 2015-2019
Recommend hosting TIMEWEB