Windows message queue handling within DLLs
I have a dll that is loaded by an application, I can not modify the source of the application (as I do not have the source) and I want to register a system wide hotkey wit开发者_C百科h the plugin. I can register the hotkey via something like RegisterHotKey(NULL, 1, MOD_CONTROL | MOD_NOREPEAT, 0x42)
(see here) but I'm not sure how I should handle the message queue, should I make a new thread and create the message handling loop when the dll initializes? Will my dll be the one receiving the messages or will the application that loaded the dll be the one, and finally is there a better way to do this?
Here's how it should be done:
- your DLL creates a thread
- this thread runs the message loop (GetMessage()/DispatchMessage()) -- that sort of thing. GetMessage() is what you really need, whereas DispatchMessage() is needed if you create a window (see below)
Now one of the two things should happen:
- the thread creates a window (hidden, perhaps) and the RegisterHotKey() function in called (doesn't matter what thread calls it) and the window handle is passed to it as the first argument
OR
- the thread created by the DLL calls RegisterHotKey(), passing NULL as the first argument.
After all this your message loop will receive the WM_HOTKEY messages. This is the official and preferred way of doing this, so no, no better ways of doing this if you're not using a framework which supports it for you (most don't).
Don't forget to call UnregisterHotKey() and kill the window and the thread when you're done.
精彩评论