How to make a Windows Cpp program listen for global hotkey presses

⌚Time: 2026-10-03 17:07:05

👨‍💻Author: Jack Ge

Sometimes you need a program to be able to listen for when a user presses a hotkey and then perform the corresponding action. The code below shows a way to implement a simple C++ program on Windows that listens for global hotkeys.

#include <windows.h>
#include <iostream>

#define HOTKEY_ID 101

int main() {
    // Register global shortcut Ctrl+Alt+A
    if (!RegisterHotKey(NULL, HOTKEY_ID, MOD_CONTROL | MOD_ALT, 'A')) {
        std::cerr << "Hotkey registered failed: " << GetLastError() << std::endl;
        return 1;
    }

    std::cout << "Hotkey registered successfully" << std::endl;

    MSG msg = {0};
    while (GetMessage(&msg, NULL, 0, 0) != 0) {
        if (msg.message == WM_HOTKEY) {
            if (msg.wParam == HOTKEY_ID) {
                std::cout << "hotkey triggered." << std::endl;
                // do something
            }
        }
    }

    UnregisterHotKey(NULL, HOTKEY_ID);
    return 0;
}