Search code examples
javaswingwinapievent-handlingjna

What's a safe way to use GetMessage or PeekMessage in Java code using JNA?


I'm trying to receive WM_HOTKEY events in my Java code. I've successfully got some throw-away code working, but I'm aware that integrating Java GUI code with a Windows message loop takes caution.

It seems from Windows examples that User32.INSTANCE.GetMessage is the key function for being notified of WM_HOTKEY events that I've registered for using User32.INSTANCE.RegisterHotKey

So...I'd like to know:

  • Have I understood correctly that RegisterHotKey and my message loop must be running on the same Java thread?
  • Have I understood correctly that Windows' GetMessage function must be called from the same thread that I use to create Windows, which is Java Swing's Event Dispatch Thread?
  • If so, I can't create a message loop on the Event Dispatch Thread, as it would block other events. Should I use PeekMessage instead?
  • If so, I would have polling code, which is not my favourite. How often should I call PeekMessage? Is PeekMessage light and fast?

Many thanks for helping a Java programmer get his head around Win API concepts.


Solution

  • Have I understood correctly that RegisterHotKey and my message loop must be running on the same Java thread?

    Yes. This is mentioned in the RegisterHotKey() documentation:

    This function cannot associate a hot key with a window created by another thread


    Have I understood correctly that Windows' GetMessage function must be called from the same thread that I use to create Windows, which is Java Swing's Event Dispatch Thread?

    Yes. A window is owned by the thread that creates it, and only the owning thread can receive messages for the window.


    If so, I can't create a message loop on the Event Dispatch Thread, as it would block other events. Should I use PeekMessage instead?

    You can, yes.


    If so, I would have polling code, which is not my favourite. How often should I call PeekMessage? Is PeekMessage light and fast?

    I would suggest creating a dedicated thread that creates its own window and uses GetMessage() for its message loop.