How do you get the current keyboard state globally? (i.e. what keys are currently depressed regardless of if the inquiring application has focus)

Deadly 提交于 2019-12-02 00:17:39

Something you can do is implement the KeyListener interface and give states to all the keys you're interested in.

If you're interested in checking if the arrow keys are depressed upon a screenshot, for instance, you can implement this KeyListener interface and override keyPressed() and keyReleased() methods and set the state for those keys you are interested in to keyPressed or keyReleased. Depending on the event. That way, when the screenshot occurs, you can just read the state of those keys

If you need this solution to be global, regardless of application focus, you could write a small hook in C that you can integrate with Java Native Interface to listen for key events. Java doesn't let you listen to key events without you attaching the listener to a component and that component having focus. Have a look at JNativeHook.

If you just need it when your application has focus but on every component you could inelegantly attach the listener to all your components or you could write your own custom KeyEventDispatcher and register it on the KeyBoardFocusManager. That way, as long as your application has focus, regardless of component that has specific focus, you could catch all keyboard events. See:

public class YourFrame extends JFrame {    

    public YourFrame() {
        // Finish all your layout and add your components
        //

        // Get the KeyboardFocusManager and register your custom dispatcher
        KeyboardFocusManager m = KeyboardFocusManager.getCurrentKeyboardFocusManager();

        m.addKeyEventDispatcher(new YourDispatcher());
    }

    private class YourDispatcher implements KeyEventDispatcher {
        @Override
        public boolean dispatchKeyEvent(KeyEvent e) {
            if (e.getID() == KeyEvent.KEY_TYPED) {
                // Do something to change the state of the key
            } else if (e.getID() == KeyEvent.KEY_PRESSED) {
                // Do something else
            }
            return false;
        }
    }

    public static void main(String[] args) {
        YourFrame yF = new YourFrame();
        yF.pack();
        yF.setVisible(true);
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!