Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 492
Arghya Chakraborty Avatar asked Aug 29 '12 12:08

Arghya Chakraborty


People also ask

Can you make a keylogger in Java?

A simple key logger application implemented in Java. It uses Native Hook library to add global listener for key presses.

How do you check if a specific key is pressed in Java?

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.

What is addKeyListener in Java?

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.


5 Answers

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.

like image 94
Site Helpers Avatar answered Oct 14 '22 21:10

Site Helpers


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);
}
like image 36
Simiil Avatar answered Oct 14 '22 21:10

Simiil


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).

like image 27
ᴇʟᴇvᴀтᴇ Avatar answered Oct 14 '22 21:10

ᴇʟᴇvᴀтᴇ


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.

like image 31
pap Avatar answered Oct 14 '22 21:10

pap


No, Java does not listen to keystokes if it's not active (focused) window, so you cannot do that.

like image 31
Valdas Avatar answered Oct 14 '22 21:10

Valdas