Kristian Kraljić You may compare programming with poetry,
a harmonic script is a piece of creativity which will last forever.
- Kristian Kraljić

Java – Global (low level) Keyboard / Mouse Hook

by Kristian Kraljic, February 9, 2016

About five years ago I started this blog by picking up an idea of Johannes Schüth (Jotschi) about a global keyboard and mouse listener for Java. Today I am very happy to announce the next major version of the library now available on GitHub!

system-hook-logo

Keyboard and mouse events in Java only work, if the registered component is in focus. For example, in case a window looses its focus (e.g. when minimized), it stops receiving any more events. Through a low-level system-wide hook it’s possible to deliver those events regardless. You’ll find all sources of the latest release, as well as binary bundles / prepackaged Java archives (JAR) on the GitHub project page.

The old post describes all changes I did to the initial version by Johannes (Jotschi). For the new major release I again reworked nearly every part of the library, to make it more stable and versatile. Here is what I did:

  • Optimized the native library C code, fixed bugs and removed all parts requireing a C++ compiler in the first place.
  • Renamed the event classes and listener interfaces and prepended Global to avoid conflicts with existing (Swing) event listeners.
  • Added support for mouseWheel events to the GlobalMouseListener.
  • Again allowed negative "out of bounds" values for GlobalMouseEvents, to also track the mouse pointer off screen (e.g. on multi-monitor setups).
  • Improved the threading concept and implemented a native error handling. The GlobalKeyboardHook and GlobalMouseHook constructors will now throw a UnsatisfiedLinkError if the native libraries can not be loaded or a RuntimeException in case hooking fails.
  • All the code has been moved to GitHub and binaries are now beeing continuously built by AppVeyor. Feel free to contribute on GitHub!

(Again) Last but not least, please share your ideas and problems in the comments. I will try to enhance the Global Keyboard / Mouse Hook based on your feedback. For the next release let’s see if we can get Linux and / or Mac OSX support going.

164 Comments

  1. Daniel says:

    I tried to create a basic GlobalKeyboardHook and kept getting this error and I don’t know how to fix it. could you help me?

    NATIVE: DllMain – DLL_PROCESS_ATTACH
    NATIVE: registerHook – Hook start
    NATIVE: registerHook – Hook failed with error 126: The specified module could not be found.

    Exception in thread “main” java.lang.RuntimeException: Low-level keyboard hook failed (-2)
    at lc.kra.system.keyboard.GlobalKeyboardHook$NativeKeyboardHook.(GlobalKeyboardHook.java:169)
    at lc.kra.system.keyboard.GlobalKeyboardHook$2.(GlobalKeyboardHook.java:89)
    at lc.kra.system.keyboard.GlobalKeyboardHook.(GlobalKeyboardHook.java:89)
    at MainClass.main(MainClass.java:7)

    • Hello Daniel, which operating system / JVM architecture are you wofking on? You get the debug output, so you downloaded one of the architecture specific packages from AppVeyor. Make sure you use the 32-bit DLLs / JAR, with a 32-bit JVM on a Windows 32-bit machine only. Use the 64-bit files, with a 64-bit JVM on a 64-bit operating system. Any other combination of those could cause the error you posted.

      Hope this helps. Regards, Kristian

    • Daniel says:

      I am running windows 10 64-bit with JVM JDK 1.8 and I made sure I downloaded the JAR file located in the Configuration: Debug; Platform: x64/ artifacts/target/system-hook-2.1.jar. I am referencing the file inside eclipse’s project folder. the same thing happened when I tried to export it and run it as an executable JAR file.

    • Hey Daniel. Hope we can figure this out. Just to be sure. Especially if you have multiple JVMs installed, it often happens that you execute on a 32-bit JVM, even if you are running it on a 64-bit operating system. Could you please check and run the following command on your console:

      java -version

      The last line should say something similar to:

      Java HotSpot(TM) 64-Bit Server VM (build 25.66-b18, mixed mode)

    • Daniel says:

      java version “1.8.0_71”
      Java(TM) SE Runtime Environment (build 1.8.0_71-b15)
      Java HotSpot(TM) 64-Bit Server VM (build 25.71-b15, mixed mode)

    • Daniel says:

      for some reason, restarting my computer solved the problem.

    • Hello Daniel, glad that helped. Sorry that I had no time to figure out the problem. Please do also see the answer I have given to Mohammad on the 3rd of March 2016, always shut down your hook properly, otherwise you run out of handles quickly.

    • Pham Trung Duc says:

      Hello Kristian Kraljic, can your lib can get the kind of the system cursor (wait, arrow, hand and other)? I have problem with it, i find by a day with no result. Thank you !

    • @Pham Trung Duc, sorry that’s not possible via the library. If you find a Windows API function to do this, feel free to extend the MouseHook.c and GlobalMouseEvent.java files and re-compile the library.

  2. John says:

    Hi. Thank you for your interested library.
    But I’m having a problem using it.
    How can I solve the Low-level keyboard hook failed?

    • Hello John, well this heavily depends on why the hooking fails. If it works for a certain amount of times and then fails, I suggest to check the answer I have given to Mohammad on the 3rd of March 2016, always shut down your hook properly, otherwise you run out of handles quickly. If this doesn’t help, please download the debug DLLs as described here, to get a extended log output.

  3. Subin says:

    Hey Kristian,
    I am getting this excepion:

    Exception in thread “Global Keyboard Hook Thread” java.lang.UnsatisfiedLinkError: lc.kra.system.keyboard.GlobalKeyboardHook$NativeKeyboardHook.registerHook()I
    Global keyboard hook successfully started, press [escape] key to shutdown.
    at lc.kra.system.keyboard.GlobalKeyboardHook$NativeKeyboardHook.registerHook(Native Method)
    at lc.kra.system.keyboard.GlobalKeyboardHook$NativeKeyboardHook.run(GlobalKeyboardHook.java:174)

    • Hello Subin, which operating system are you using? Are you using the pre-bundled JAR file or do you run the .class / .java files stand-alone? Could you please go to console (cmd), execute the following two commands and paste the result here?

      systeminfo | findstr /B /C:"OS Name" /C:"OS Version" /C:"System Type"
      java -version

  4. TT says:

    ty for ur project …. it’s work perfectly :)

  5. Rana says:

    I am getting this error too:

    Exception in thread “Global Keyboard Hook Thread” java.lang.UnsatisfiedLinkError: lc.kra.system.keyboard.GlobalKeyboardHook$NativeKeyboardHook.registerHook()I
    at lc.kra.system.keyboard.GlobalKeyboardHook$NativeKeyboardHook.registerHook(Native Method)
    at lc.kra.system.keyboard.GlobalKeyboardHook$NativeKeyboardHook.run(GlobalKeyboardHook.java:174)

    • Hello Rana, same for you. Which operating system are you using? Are you using the pre-bundled JAR file or do you run the .class / .java files stand-alone? Could you please go to console (cmd), execute the following two commands and paste the result here?

      systeminfo | findstr /B /C:"OS Name" /C:"OS Version" /C:"System Type"
      java -version

  6. Roland says:

    Hello. Will there be support for Linux in the future? If there isn’t right now (or the next 3 to 6 months) that’s okay for me, but I do need it in the future. A Java cross-platform global keylistener would be freakin’ awesome! :D

    • Hello Roland. Linux and Mac support are planned, but I didn’t find the time to implement this yet. Especially because Linux low-level keyboard / mouse hooks are quite tedious to implement. You can watch the GitHub repository to get notified on any updates! Hope this helps. :-)

    • Roland says:

      Hmm.. Yes I was afraid this might be tough stuff. Do you have any idea when (roughly) support for Linux might ready? Just so I have an idea. Could it still happen some time this year?

      Keep up the good work! :)

    • Sorry, I can’t make any promises… This year is really packed. Mostly I’m finding my “Qi” nearing the end of year. Just look at my other blog posts, they are mostly written in December. :-) Hope that’s fine anyways, I’ve been looking forward to a Linux support for a long time.

  7. Kundan Suthar says:

    I ma getting below error while running command “mvn clean install” , [please help (OS – windows 7 64 bit , jdk 1.8)

    [ERROR] Failed to execute goal org.apache.maven.plugins:maven-antrun-plugin:1.8:
    run (compile-native) on project system-hook: An Ant BuildException has occured:
    The following error occurred while executing this line:
    [ERROR] C:\Users\Remedies\Downloads\system-hook-master\system-hook-master\build.
    xml:115: Could not launch gcc: java.io.IOException: Cannot run program “gcc” (in
    directory “C:\Users\Remedies\Downloads\system-hook-master\system-hook-master\ta
    rget\objects”): CreateProcess error=2, The system cannot find the file specified

    [ERROR] around Ant part …… @ 4:8 in C:\Users\Remedies\Downloads\system-
    hook-master\system-hook-master\target\antrun\build-main.xml
    [ERROR] -> [Help 1]

    • Hello Kundan, if you’d like to build the library a C99 compatible compiler / linker bundle is required to build the native libraries, see MSYS2. In case you didn’t do any modification to the code, there is no need for building the library from scratch. You may go to the releases section on GitHub and download a pre-bundled JAR. Hope this helps.

  8. aszdf says:

    alert(“hello”);

  9. Gustavo says:

    Hi, Kristian very usefull library, congrats. Is there a way to read a keyboard event and stop the event of the key pressed? And is there a way to identify the keyboard?

    I want to use a numeric keypad for identification and the key events in that keyboard must be catch only in my application. Is there a way to do that?

    Thanks

  10. Conan says:

    on Win10, got message:-

    Exception in thread “Global Keyboard Hook Thread” java.lang.UnsatisfiedLinkError: lc.kra.system.keyboard.GlobalKeyboardHook$NativeKeyboardHook.registerHook()I
    at lc.kra.system.keyboard.GlobalKeyboardHook$NativeKeyboardHook.registerHook(Native Method)
    at lc.kra.system.keyboard.GlobalKeyboardHook$NativeKeyboardHook.run(GlobalKeyboardHook.java:174)
    Exception in thread “Global Mouse Hook Thread” java.lang.UnsatisfiedLinkError: lc.kra.system.mouse.GlobalMouseHook$NativeMouseHook.registerHook()I
    at lc.kra.system.mouse.GlobalMouseHook$NativeMouseHook.registerHook(Native Method)
    at lc.kra.system.mouse.GlobalMouseHook$NativeMouseHook.run(GlobalMouseHook.java:196)
    Global keyboard&mouse hook successfully started, press [escape] key to shutdown.