Java System-Wide Keyboard Shortcut

后端 未结 7 791
北海茫月
北海茫月 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:35

    I just found https://github.com/kwhat/jnativehook

    Seems to be cross platform.

    Here's their sample code for listening for key presses:

    import org.jnativehook.GlobalScreen;
    import org.jnativehook.NativeHookException;
    import org.jnativehook.keyboard.NativeKeyEvent;
    import org.jnativehook.keyboard.NativeKeyListener;
    
    public class GlobalKeyListenerExample implements NativeKeyListener {
        public void nativeKeyPressed(NativeKeyEvent e) {
            System.out.println("Key Pressed: " + NativeKeyEvent.getKeyText(e.getKeyCode()));
    
            if (e.getKeyCode() == NativeKeyEvent.VC_ESCAPE) {
                GlobalScreen.unregisterNativeHook();
            }
        }
    
        public void nativeKeyReleased(NativeKeyEvent e) {
            System.out.println("Key Released: " + NativeKeyEvent.getKeyText(e.getKeyCode()));
        }
    
        public void nativeKeyTyped(NativeKeyEvent e) {
            System.out.println("Key Typed: " + e.getKeyText(e.getKeyCode()));
        }
    
        public static void main(String[] args) {
            try {
                GlobalScreen.registerNativeHook();
            }
            catch (NativeHookException ex) {
                System.err.println("There was a problem registering the native hook.");
                System.err.println(ex.getMessage());
    
                System.exit(1);
            }
    
            GlobalScreen.addNativeKeyListener(new GlobalKeyListenerExample());
        }
    }
    

    Checking for modifiers is based on bit masks (stuff we all should know but always forget :-P):

        boolean isAltPressed = (e.getModifiers() & NativeKeyEvent.ALT_MASK) != 0;
        boolean isShiftPressed = (e.getModifiers() & NativeKeyEvent.SHIFT_MASK) != 0;
    

    This you could combine with KeyCode:

    if (e.getKeyCode() == NativeKeyEvent.VK_2 && isShiftPressed && isAltPressed){...}
    

    This is modified example from here

    You should also modify the default logging behavior otherwise it will spam the console:

    // Get the logger for "org.jnativehook" and set the level to warning.
    Logger logger = Logger.getLogger(GlobalScreen.class.getPackage().getName());
    logger.setLevel(Level.WARNING);
    
    // Don't forget to disable the parent handlers.
    logger.setUseParentHandlers(false);
    

    Code example is from here

    0 讨论(0)
提交回复
热议问题