Windows10 Home / JDK1.8
<dependency>
<groupId>com.1stleg</groupId>
<artifactId>jnativehook</artifactId>
<version>2.1.0</version>
</dependency>
import org.jnativehook.GlobalScreen;
import org.jnativehook.NativeHookException;
import org.jnativehook.keyboard.NativeKeyEvent;
import org.jnativehook.keyboard.NativeKeyListener;
public class Example implements NativeKeyListener {
public static void main(String[] args) {
//If not hooked
if (!GlobalScreen.isNativeHookRegistered()) {
try {
//Register hook
GlobalScreen.registerNativeHook();
} catch (NativeHookException e) {
e.printStackTrace();
System.exit(-1);
}
}
//Register key listener
GlobalScreen.addNativeKeyListener(new Example());
}
//When you press a key
@Override
public void nativeKeyPressed(NativeKeyEvent e) {
System.out.println(e.paramString());
}
//When you release the key
@Override
public void nativeKeyReleased(NativeKeyEvent e) {
System.out.println(e.paramString());
}
//When you type the key
@Override
public void nativeKeyTyped(NativeKeyEvent e) {
System.out.println(e.paramString());
}
}
This code allows you to have a key listener for all running threads, not just the thread running this code.
The event will occur no matter which software you press the key on, such as Chrome or Minecraft.
Also, each key event constant is the same as each java.awt.event.KeyListener constant.
//Mouse listener
GlobalScreen.addNativeMouseListener(NativeMouseListener);
//Mouse motion listener
GlobalScreen.addNativeMouseMotionListener(NativeMouseMotionListener);
//Mouse wheel listener
GlobalScreen.addNativeMouseWheelListener(NativeMouseWheelListener);
And mouse related listeners are available.
By default, a considerable amount of logs are output, so if you do not need it LogManager.getLogManager().reset(); Let's add even around the main method.
There is a paramString () method, so let's use it.
Recommended Posts