Here is a simplified Windows console program.
#include <windows.h>
#include <stdio.h>
#include <time.h>
#define VK_K 0x4b
int main (int argc, char**argv) {
srand((unsigned int)time(NULL));
int id =rand();
BOOL ret =RegisterHotKey(NULL, id, MOD_SHIFT|MOD_WIN, VK_K);
printf("ret=%d; id=%d\n", ret, id);
MSG msg ={0};
while (GetMessage(&msg, NULL, 0, 0) != 0) {
if (msg.message==WM_HOTKEY) {
printf("Got it; quitting.\n");
break;
}
}
return 0;
}
It registers a global hotkey (Shift+Win+K) and then loops until it gets a WM_HOTKEY message (which in this case should only happen when the aforementioned hotkey is pressed).
It works… for the most part. The problem is that if you run a second instance of the program while the first one is in the loop, then instead of failing, the second instance successfully registers the hotkey. If you then press the key, the second instance catches it and quits. If you then press it again, the first instance gets it. (This works for multiple instances in a FILO manner.)
I thought that maybe it has something to do with a remark in the
RegisterHotkey page on MSDN about using the same HWND-id combination, however it is not using the same HWND-id combination (unless for some reason, a NULL HWND counts). Besides, the id is randomized. Also, I can register the same hotkey from a different, Windows app that uses a non-NULL HWND and different id (while the console app is active), so it’s definitely not being reserved.
Why
isn’t the call to
RegisterHotkey
failing?