Running program in the background

Asked

Viewed 1,804 times

4

How to run a program in the background, and when the user presses a key the program does something?

I only know how to do with the program in focus.

  • 1

    If I understand correctly, you want your application to monitor the keys that are pressed, regardless of whether it is focused or not. Doing this is not something so trivial, you could try using the library jnativehook, if that’s what you’re looking for I can put as an answer.

2 answers

2

I believe you want to run part of your program in another Thread.

Take a look at the Thread class.

In the method triggered by clicking the button, you run the task in another Thread while the Main Thread continues.

new Thread() {
    @Override
    public void run() {
        // Seu código aqui
    }

}.start();

1


In accordance with commenting, you can use the library Jnativehook, follows demo code that is on the library’s own page.

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());
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.