没有JFrame,有没有办法获取键盘事件? [英] 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?
推荐答案
这可能会做您想要的.请注意,此代码正在检查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...
这篇关于没有JFrame,有没有办法获取键盘事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!