Is there a way to get keyboard events without JFrame?

喜你入骨 提交于 2019-12-01 07:31:16

问题


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?


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




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




回答3:


A solution to do this by using a JFrame is to set his opacity to 0.0 and to add the Keylistener to it. But the user will see an icon in his shortcut bar...



来源:https://stackoverflow.com/questions/4609068/is-there-a-way-to-get-keyboard-events-without-jframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!