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

Arghya Chakraborty picture Arghya Chakraborty · Aug 29, 2012 · Viewed 65k times · Source

I want to write a key listener in Java. It should track all the key presses regardless of whether the Java app has focus or not. Is this possible?

Answer

Simiil picture Simiil · Aug 29, 2012

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);
}