kwhat / jnativehook

Global keyboard and mouse listeners for Java.
Other
1.75k stars 348 forks source link

Is it possible for the Windows key to be consumed? #413

Closed trdesilva closed 2 years ago

trdesilva commented 2 years ago

I'm trying to add functionality to my project that temporarily "disables" the Windows key. I saw that consuming events with jnativehook is possible but unsupported, so I was wondering if this was expected to work in my scenario. I tried it on version 2.2 with Windows 10 running OpenJDK 11, and the event is caught, but my Start menu still opens. I mostly copied the sample code from the documentation, setting the reserved field on the event to 0x01, and no exception is thrown. My source code is here: https://github.com/trdesilva/autorecorder/blob/task-54/src/io/github/trdesilva/autorecorder/video/BookmarkListener.java#L109

leandrocm86 commented 2 years ago

I came to the Issues session to know if the event consuming was working on windows and wayland. I'm not sure I understood the docs correctly and how to use the VoidDispatchService. Have you tried with any other key? Is this a specific problem with the Win key or with the consuming mechanism?

trdesilva commented 2 years ago

Turns out that my issue was just forgetting to set the event dispatcher to the VoidDispatchService, so thanks for mentioning that. I tested the Windows key and the A key on jnativehook 2.2.0 and 2.2.2, and all combinations worked.

Using the VoidDispatchService seems pretty straightforward--just call GlobalScreen.setEventDispatcher(new VoidDispatchService()) before registerNativeHook() and addNativeKeyListener() instead of using whatever event dispatcher you would otherwise. Make sure that if your NativeKeyListener implementation needs to do any work when it gets an event, it does it asynchronously, because you'll introduce input lag otherwise. With the VoidDispatchService, the key event doesn't propagate until your callback finishes.