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;
}