Eric Pauley
Eric Pauley

Reputation: 1779

Capturing global key presses with java.awt.Toolkit

I found the method addAWTKeyListener in the class Toolkit, but I can't get it to work properly, whether or not the window has focus. My code is as follows:

import java.awt.AWTEvent;
import java.awt.Toolkit;
import java.awt.event.AWTEventListener;
import java.awt.event.KeyEvent;


public class KeyTest {

    public static void main(String[] args){
    Thread t = new Thread(){
        @Override
        public void run() {
        System.out.println("STARTING");
        Toolkit kit = Toolkit.getDefaultToolkit();
        kit.addAWTEventListener(new AWTEventListener(){

            @Override
            public void eventDispatched(AWTEvent event) {
            System.out.println("EVENT");
            if(event instanceof KeyEvent){
                KeyEvent kEvent = (KeyEvent) event;
                System.out.println(kEvent.getKeyCode());
            }
            }

        }, AWTEvent.KEY_EVENT_MASK);
        while(true);
        }
    };
    t.start();
    }

}

Is there something I'm doing wrong? I get to the point that STARTING prints and there are no errors. The even is simply not called.

Upvotes: 1

Views: 1292

Answers (2)

kaempfer0080
kaempfer0080

Reputation: 26

I may be wrong as I'm certainly not an expert, but as far as I know what you're trying to do isn't possible in Java.

Are you trying to capture a key click using a Java program, but without creating a window? Part of Java's security, and this is what I may be wrong on, is that it can only listen to events inside Java windows created by that particular Java program.

So if you were trying to make something key-logger-esque that runs in the background and captured a key press, it wouldn't be able to do that.

I wish I could give you a more concrete answer but I hope this helped.

Upvotes: 1

John3136
John3136

Reputation: 29266

Just a guess, but you your sample doesn't have any AWT windows in it, so I'm guessing that is why the event never gets fired.

When you say "whether or not the window has focus" does your real app have windows that you have chopped out, or are you talking about a java console window or similar?

Upvotes: 1

Related Questions