Question

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!

Was it helpful?

Solution

So RegisterHotKey needs to be called from the same thread that created the window and started the message loop. Why not inject the execution of RegisterHotKey into 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.Invoke which will marshal that delegate onto the thread hosting the ISynchronizeInvoke instance. Here is how it might be done.

void Main()
{
  var f = new Form();

  // Start your custom message loop here.
  new Thread(
    () =>
    {
      var nw = NativeWindow.FromHandle(f.Handle);
      Application.Run(new ApplicationContext(f));
    }

  // This can be called from any thread.
  f.Invoke(
    (Action)(() =>
    {
      RegisterHotKey(/*...*/);
    }), null);
}

I do not know...maybe you will want to call UnregisterHotKey as 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 Form instance created then you could probably get away with submitting a custom message to the thread via SendMessage and the like and processing it in NativeWindow.WndProc to get the same effect that the ISynchronizeInvoke methods provide automatically.

OTHER TIPS

I don't know if there's a better way, but you could use a Mutex and reset it when you call Application.Run and use Mutex.Wait() when calling Applicationcontext.ExitThread().

You might try waiting until the Application.Idle Event is fired to allow the user to call RegisterHotKey.

I know this thread is old, but I came here when trying to resolve an issue and spent some time looking at the accepted answer. It is of course basically correct, but as it stands the code doesn't compile, doesn't start the thread it creates, and even if we fix that it calls f.Invoke before f is created, so throws exceptions.

I fixed all that up and working code is below. I'd have put it in a comment on the answer but I don't have sufficient rep. Having done that, I'm a little unsure of the validity of forcing the form to be created before calling Application.Run in this way, or of doing 'new Form' on one thread and then passing it to another to be fully created (particularly since this is easily avoided):

static void Main(string[] args)
{
    AutoResetEvent are = new AutoResetEvent(false);
    Form f = new Form();
    Console.WriteLine(Thread.CurrentThread.ManagedThreadId);

    new Thread(
        () =>
        {
            Console.WriteLine(Thread.CurrentThread.ManagedThreadId);
            var nw = NativeWindow.FromHandle(f.Handle);
            are.Set();
            Application.Run(f);
        }).Start();

    are.WaitOne(new TimeSpan(0, 0, 2));

    f.Invoke(
        (Action)(() =>
        {
            Console.WriteLine(Thread.CurrentThread.ManagedThreadId);
        }), null);

    Console.ReadLine();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top