Alright guys, so right now I'm working on a program that finds the current focused window and adds a KeyListener to it. The problem is that unlike when you have a window running and you add a KeyListener to it and it stays working until you close the window, once I add the KeyListener to the focused window my program ends. What I want to do is to keep it running, that way whenever a key is presses the mouse will make a click. Here is my code:

import java.awt.KeyboardFocusManager;
import java.awt.Robot;
import java.awt.Window;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

public class TestClass implements KeyListener{

    private KeyboardFocusManager m;
    private Window w;

    public void setUp(){
        try{
            Thread.sleep(5000);
            m = KeyboardFocusManager.getCurrentKeyboardFocusManager();
            w = m.getFocusedWindow();
            w.addKeyListener(this);
        }catch(Exception e){}
    }
    public void keyPressed(KeyEvent event){
        try{
            Robot robot = new Robot();
            robot.mousePress(16);
            robot.delay((int) Math.random()*150);
            robot.mouseRelease(16);
        }catch(Exception e){}
    }
    public void keyReleased(KeyEvent event){}
    public void keyTyped(KeyEvent event){}

    public static void main(String[] args){
        new TestClass().setUp();
    }
}

Is there a way to listen to key events outside a window?

Hi

Is there a way to listen to key events outside a window?

As far as I now it is not possible to listen to even outside window using Java.
This could be done by using JNI .

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.