I am trying to make a program that can detect my key strokes then based on them do something but every time I run my program it just finishes with exit code 0 even though I have the listeners initialized any ideas? (I got no errors)
public class Main {
public static void main(String[] args) {
InitializeEvents initializeEvents = new InitializeEvents();
try {
GlobalScreen.registerNativeHook();
} catch (NativeHookException e) {
e.printStackTrace();
}
GlobalScreen.getInstance().addNativeKeyListener(initializeEvents.getKeyboard());
GlobalScreen.getInstance().addNativeMouseListener(initializeEvents.getMouse());
}
}
Here is where I initialize my event
public class InitializeEvents {
private final NativeKeyboardEvent keyboard;
private final NativeMouseClickEvent mouse;
public InitializeEvents() {
keyboard = new NativeKeyboardEvent();
mouse = new NativeMouseClickEvent();
}
public NativeKeyboardEvent getKeyboard() {
return keyboard;
}
public NativeMouseClickEvent getMouse() {
return mouse;
}
}
Lastly here is my event
public class NativeKeyboardEvent implements NativeKeyListener {
@Override
public void nativeKeyPressed(NativeKeyEvent e) {
System.out.println("test");
}
@Override
public void nativeKeyReleased(NativeKeyEvent e) {
System.out.println("test");
}
@Override
public void nativeKeyTyped(NativeKeyEvent e) {
System.out.println("test");
}
}
The weird thing about it is that it was working earlier but then it randomly stopped printing "test" when I clicked a key even though nothing changed.
As soon as your application no longer has any non-daemon threads running, it will terminate. You can easily validate this by putting
while(true) {
Thread.sleep(Long.MAX_VALUE);
}
on the last line in your main
method. Eventually, I can imagine that your application will either have an active window or a taskbar icon that keeps it alive and that adds an application quit option, replacing the need for this temporary solution.