Running program in the background

4

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.

    
asked by anonymous 19.01.2015 / 00:06

2 answers

1

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());
    }
}
    
30.01.2015 / 01:37
2

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();
    
19.01.2015 / 02:11