且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

没有JFrame,有没有办法获取键盘事件?

更新时间:2022-05-09 01:01:53

这可能会做您想要的.请注意,此代码正在检查Ctr-F击键.我使用此代码从应用程序中的任何内容打开查找对话框.我很确定该应用程序必须具有重点.至少要尝试一下...

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);

我想我明白你想要什么.基本上是当应用程序没有焦点时.如果是这样,那么您可能必须使用本机API(JNI)介入操作系统事件,但这会迫使您进入特定的操作系统...

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