I have to write an C# API for registering global hotkeys. To receive the WM_HOTKEY message, I use a System.Windows.Forms.NativeWindow and run an own message loop with System.Windows.Forms.Application.Run(ApplicationContext). When the user wants to register a hotkey, he has to run a method called RegisterHotkey() which stops the message loop with System.Windows.Forms.ApplicationContext.ExitThread(), registers the hotkey with the RegisterHotKey() (P/Invoke) function and starts the message loop again. This is required, because RegisterHotKey() must be called within the same thread that created the window, which again must be instantiated within the same thread that runs the message loop.
The problem is, that if the user calls the RegisterHotkey() method shortly after starting the thread which is running the message loop, ApplicationContext.ExitThread() gets called before Application.Run(ApplicationContext) and therefore the application blocks indefinitely. Does anybody know an approach for waiting for a message loop to be started?
Thanks in advance!
So
RegisterHotKeyneeds to be called from the same thread that created the window and started the message loop. Why not inject the execution ofRegisterHotKeyinto your custom message loop thread? That way you do not need to stop and restart the message loop. You can just reuse the first one you started and avoid the strange race conditions at the same time.You can inject a delegate onto another thread using
ISynchronizeInvoke.Invokewhich will marshal that delegate onto the thread hosting theISynchronizeInvokeinstance. Here is how it might be done.I do not know…maybe you will want to call
UnregisterHotKeyas well depending on the behavior you are after. I am not that familiar with these APIs so I cannot comment on how they might be used.If you do not want that arbitrary
Forminstance created then you could probably get away with submitting a custom message to the thread viaSendMessageand the like and processing it inNativeWindow.WndProcto get the same effect that theISynchronizeInvokemethods provide automatically.