Java System-Wide Keyboard Shortcut

后端 未结 7 836
北海茫月
北海茫月 2020-12-01 04:12

Is there any way or a library to get a system-wide (global) keyboard shortcut to perform an action in a Java application?

7条回答
  •  孤城傲影
    2020-12-01 04:27

    UPDATE: I don't know if you can hook events from OUTSIDE the JVM. I think a Swing/AWT component must have focus for this to work.

    You'll want to hook in the Java AWT Event Queue to be absolutely sure you can get a global (jvm wide) keypress.

    Use

    EventQueue ev = Toolkit.getSystemEventQueue();
    // MyCustomEventQueue extends EventQueue and processes keyboard events in the dispatch
    ev.push(new MyCustomEventQueue());
    
    class MyEventQueue extends EventQueue
    {
        protected void dispatchEvent(AWTEvent event)
        {
           // all AWTEvents can be indentified by type, KeyEvent, MouseEvent, etc
           // look for KeyEvents and match against you hotkeys / callbacks
        }
    }
    

    I think there may be other ways to accomplish global key presses with action maps. I've actually used the above mether

提交回复
热议问题