How can I write a key listener to track all keystrokes in Java? [closed]

It's possible but requires an implementation taking advantage of JNI which will not always be portable.

Java System Hook is one such library that will work with Windows 32 & 64 bit.


I used something like that a while ago. Take a look at Java System Hook.

It tracks global key presses (not just your Java application) via JNI. It worked fast and perfectly for me


The KeyListener starts as a daemon thread, which does not keep the application alive. You have to have another running non-daemon thread in your program

For example:

GlobalKeyListener globalKeyListener = new GlobalKeyListener();
globalKeyListener.addKeyListener(listener);
while (true) {
    Thread.sleep(1000);
}

No, Java does not have access to key-strokes outside of its active window.

To achieve this, you would have to use a combination of Java and native code, using JNI to call the native code. In Microsoft Windows, you should look at GetAsyncKeyState(key).