Is there a way to get keyboard events without JFrame?

12,696

Solution 1

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...

Solution 2

This might be useful. I'm not sure if there is one library that will work for Windows/Linux/Mac. For Windows you will need some external library that uses native code to create a keyboard hook. I have no idea how to do it on the other OSes.

Share:
12,696
Rogach
Author by

Rogach

Updated on August 21, 2022

Comments

  • Rogach
    Rogach over 1 year

    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?