Click here to Skip to main content
15,880,608 members
Please Sign up or sign in to vote.
4.00/5 (2 votes)
See more:
Here is a simplified Windows console program.
C++
#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?
Posted
Updated 9-Jun-11 23:29pm
v2
Comments
Mark Salsbery 9-Jun-11 18:52pm    
Are you sure your "random" number is unique every time? I would call srand((unsigned)time(NULL)); before using rand()...
Synetech 12-Jun-11 0:02am    
Yes, I’ve seen it “be different” in a debugger.
strogg 12-Jun-11 15:01pm    
Strange, i've used this in a win app, not a console. RegisterHotKey successfully fails (returns 0) when another instance calls it. I think you're experiencing this behavior because you're passing NULL as the window handle. If you have the time, create a hidden window just for the purpose of handling messages & try. The second instance will probably fail then
Synetech 16-Jun-11 21:48pm    
Yup, that works. I created a dummy (message-only) window and used its handle to register the hotkey and it subsequent instances (and other programs) fail.

Thanks; this work-around for will certainly work now. Of course, it’s still curious why it didn’t work as expected since the MSDN docs indicate that a NULL HWND is valid.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900