How to run a program in the background, and when the user presses a key does the program do something?
I can only do with the program in focus.
How to run a program in the background, and when the user presses a key does the program do something?
I can only do with the program in focus.
As comment , you can use the < a href="https://code.google.com/p/jnativehook/"> JNativeHook , it follows demo code that is on the library page itself.
import org.jnativehook.GlobalScreen;
import org.jnativehook.NativeHookException;
import org.jnativehook.keyboard.NativeKeyEvent;
import org.jnativehook.keyboard.NativeKeyListener;
public class GlobalKeyListenerExample implements NativeKeyListener {
public void nativeKeyPressed(NativeKeyEvent e) {
System.out.println("Key Pressed: " + NativeKeyEvent.getKeyText(e.getKeyCode()));
if (e.getKeyCode() == NativeKeyEvent.VK_ESCAPE) {
GlobalScreen.unregisterNativeHook();
}
}
public void nativeKeyReleased(NativeKeyEvent e) {
System.out.println("Key Released: " + NativeKeyEvent.getKeyText(e.getKeyCode()));
}
public void nativeKeyTyped(NativeKeyEvent e) {
System.out.println("Key Typed: " + e.getKeyText(e.getKeyCode()));
}
public static void main(String[] args) {
try {
GlobalScreen.registerNativeHook();
}
catch (NativeHookException ex) {
System.err.println("There was a problem registering the native hook.");
System.err.println(ex.getMessage());
System.exit(1);
}
//Construct the example object and initialze native hook.
GlobalScreen.getInstance().addNativeKeyListener(new GlobalKeyListenerExample());
}
}
I believe you want to run part of your program on another Thread.
Take a look at the Thread class.
In the method triggered by the click of the button, you execute the task on another Thread while the Main Thread continues.
new Thread() {
@Override
public void run() {
// Seu código aqui
}
}.start();