Search code examples
javaswingkeyboardkeyboard-eventsevent-listener

Is there a way to get keyboard events without JFrame?


I want to get my program to unhide main window when user presses some shortcut. Is there a way to get the global key events, not only the ones which happened when focus was inside application frame?


Solution

  • This might do what you want. Note that this code is checking for a Ctr-F keystroke. I use this code to open up a find dialog from anything in the application. I'm pretty sure that the app has to have focus though. Something to try at least...

    AWTEventListener listener = new AWTEventListener() {
      @Override
      public void eventDispatched(AWTEvent event) {
        try {
          KeyEvent evt = (KeyEvent)event;
          if(evt.getID() == KeyEvent.KEY_PRESSED && evt.getModifiers() == KeyEvent.CTRL_MASK && evt.getKeyCode() == KeyEvent.VK_F) {
    
          }
        }
        catch(Exception e) {
          e.printStackTrace();
        }
      }
    };
    
                Toolkit.getDefaultToolkit().addAWTEventListener(listener, AWTEvent.KEY_EVENT_MASK);
    

    EDIT: I think I understand what you want. Basically when the app does NOT have focus. If so then you'll probably have to hook into the OS events with a native API (JNI) but that forces you to a specific OS...