java 有没有办法在没有 JFrame 的情况下获取键盘事件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4609068/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there a way to get keyboard events without JFrame?
提问by Rogach
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?
我想让我的程序在用户按下某个快捷方式时取消隐藏主窗口。有没有办法获取全局关键事件,而不仅仅是焦点在应用程序框架内时发生的事件?
回答by Merky
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...
这可能会做你想做的。请注意,此代码正在检查 Ctr-F 击键。我使用此代码从应用程序中的任何内容打开查找对话框。我很确定该应用程序必须具有焦点。至少要尝试一些东西......
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...
编辑:我想我明白你想要什么。基本上当应用程序没有焦点时。如果是这样,那么您可能必须使用本机 API (JNI) 连接到操作系统事件,但这会迫使您使用特定的操作系统...
回答by Sebastian ?askawiec
Thismight 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.
这可能有用。我不确定是否有一个适用于 Windows/Linux/Mac 的库。对于 Windows,您将需要一些使用本机代码创建键盘挂钩的外部库。我不知道如何在其他操作系统上做到这一点。
回答by Sama Rive
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...
使用 JFrame 执行此操作的解决方案是将其不透明度设置为 0.0 并将 Keylistener 添加到其中。但是用户会在他的快捷方式栏中看到一个图标......