tags:

views:

82

answers:

2

I have a program that sets a global keyboard hook and handles key presses. This is my WinMain:

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR pCmdLine, int nCmdShow)
{
  MSG msg;
  logFile = fopen("C:\\keylog.txt", "w");
  hKeyHook = SetWindowsHookEx(WH_KEYBOARD_LL, (HOOKPROC)KeyEvent, GetModuleHandle(NULL), 0);

  GetMessage(&msg, NULL, 0, 0);

  UnhookWindowsHookEx(hKeyHook);
  fclose(logFile);
  return 0;
}

Since it doesn't create any windows it won't ever receive a window message, so GetMessage would stall the program, and it is very light on CPU cycles. However, when it detects a certain key is pressed I want it to exit the program. I can't broadcast a message because it won't receive it. If I do something like:

while(State == true)
  Sleep(500);

The program itself and the global hook would stall and this is undesirable. Making it Sleep(0) makes it consume an unmanageable amount of CPU cycles.

So, what is the best alternative for my problem? The only thing I can think of is going through the trouble to register my own window class and create a window to receive the message, but perhaps there is a better way?

+5  A: 

why not create synchronization object (maybe Event) and replace GetMessage with WaitForSingleObject. You can easily make your keyboard hook routine trigger the object and your app will do the pre-termination stuff.

YeenFei
+3  A: 

You cant broadcast a message using HWND_BROADCAST.

You don't need a window to receive messages however: if you had some way to publish your thread id, then PostThreadMessage() could be used to send a message (probably a WM_QUIT) to your app.

Chris Becke
GetCurrentThreadId() works to get the thread id.
kaykun
Wait.. What? Don't you need a message queue to exist in the receiving thread to receive messages? Why would a console app have a message queue?
Moron
1. yes. 2. it wouldn't normally. But no matter. A message queue is created on demand as soon as a message queue API is called: GetMessage() for example will ensure there is a message queue associated with the thread.
Chris Becke