Question

I'm trying to catch some keyboard event globally without using any window like JFrame, it should either a console app or a service (demon). Here is code I have:

class Main extends Thread {
    public void run() {
        AWTEventListener listener = new AWTEventListener() {
            @Override
            public void eventDispatched(AWTEvent event) {
                try {
                    if (event instanceof KeyEvent) {
                        KeyEvent evt = (KeyEvent) event;
                        if (evt.getID() == KeyEvent.KEY_PRESSED &&
                                evt.getModifiers() == KeyEvent.CTRL_MASK &&
                                evt.getKeyCode() == KeyEvent.VK_F) {
                            System.out.println("Ctrl+F is pressed!");
                        }
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };

        Toolkit.getDefaultToolkit().addAWTEventListener(listener, AWTEvent.KEY_EVENT_MASK);
        System.out.println("Listening to hotkeys...");
        while (true) {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }
        }
    }

    public static void main(String[] args) {
        Main b = new Main();
        b.start();
    }
}  

However, when I start it, it does nothing but printing "Listening to hotkeys..." when I press Ctrl+F. Even when I make a focus to other application or desktop, the result is still the same.

How did I do wrong?

Était-ce utile?

La solution

class Main extends Thread { public void run() {

    AWTEventListener listener = new AWTEventListener() {
        @Override
        public void eventDispatched(AWTEvent event) {
            try {
                if (event instanceof KeyEvent) {
                    KeyEvent evt = (KeyEvent) event;
                    if (evt.getID() == KeyEvent.KEY_PRESSED &&
                            evt.getModifiers() == KeyEvent.CTRL_MASK &&
                            evt.getKeyCode() == KeyEvent.VK_F) {
                        System.out.println("Ctrl+F is pressed!");
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };
            Toolkit.getDefaultToolkit().addAWTEventListener(listener, AWTEvent.KEY_EVENT_MASK|AWTEvent.ACTION_EVENT_MASK);


}


public static void main(String[] args) {
new JFrame("").setVisible(true);
    Main b = new Main();
    b.start();
}

}

This is working. You can not use while loop like you have used in your program..

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top