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?
A simple key logger application implemented in Java. It uses Native Hook library to add global listener for key presses.
If you want to test whether the key that the user pressed is the Shift key, you could say "if (evt. getKeyCode() == KeyEvent. VK_SHIFT)". The key codes for the four arrow keys are KeyEvent.
The listener object created from that class is then registered with a component using the component's addKeyListener method. A keyboard event is generated when a key is pressed, released, or typed. The relevant method in the listener object is then invoked, and the KeyEvent is passed to it.
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)
.
It's very much possible, but not using standard Java, you have to interact with the operating system on a native level.
Here is a topic for Windows that uses JNA to access the SetWindowsHookEx function in the Windows User32 API.
No, Java does not listen to keystokes if it's not active (focused) window, so you cannot do that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With