java 如何在java中捕获全局按键
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16179923/
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
How to capture global key presses in java
提问by Snehasish
I made a simple Media player in Java but I want to record global key presses like Ctrl+ Pto pause/resume the current music being played without the JFrame having focusbut it seems that its not possible due to JVM security issues.
我用 Java 制作了一个简单的媒体播放器,但我想记录像Ctrl+这样的全局按键P来暂停/恢复当前正在播放的音乐,而 JFrame 没有焦点,但由于 JVM 安全问题,这似乎是不可能的。
I came across JNativeHookbut I want to implement my own method only for Windows. Please Suggest how to do it and where to begin ?
我遇到了JNativeHook,但我只想为 Windows 实现我自己的方法。请建议如何做以及从哪里开始?
采纳答案by Nikola Yovchev
Jintellitype is a somewhat easy solution.
Jintellitype 是一个比较简单的解决方案。
https://code.google.com/p/jintellitype/
https://code.google.com/p/jintellitype/
The other easy solution would be to use a windows hook with JNA:
另一个简单的解决方案是使用带有 JNA 的 windows 钩子:
I have some experience with JNA and have really liked the api.
我对 JNA 有一些经验,并且非常喜欢这个 api。
And a third solution would be to manage your own calls with JNI.
第三种解决方案是使用 JNI 管理您自己的调用。
Portability-wise, as far as I know, windows dlls and api architecture as far as responding to user input, has been preserved in different OS versions. If memory serves, hooks for user input are in the user32 dll. Maybe you have to jump through some hoops for a x64 bit version, but I doubt it would be that hard.
在可移植性方面,据我所知,就响应用户输入而言,Windows dll 和 api 架构已保留在不同的操作系统版本中。如果没记错的话,用户输入的钩子在 user32 dll 中。也许您必须为 x64 位版本跳过一些障碍,但我怀疑这会很难。
回答by Thunder
Try JNativeHook. Here is a sample that shows how to use it to capture global key presses:
试试JNativeHook。这是一个示例,展示了如何使用它来捕获全局按键:
try
{
GlobalScreen.registerNativeHook();
GlobalScreen.addNativeKeyListener(new NativeKeyListener()
{
@Override
public void nativeKeyTyped(NativeKeyEvent nativeEvent)
{
}
@Override
public void nativeKeyReleased(NativeKeyEvent nativeEvent)
{
String keyText=NativeKeyEvent.getKeyText(nativeEvent.getKeyCode());
System.out.println("User typed: "+keyText);
}
@Override
public void nativeKeyPressed(NativeKeyEvent nativeEvent)
{
}
});
}
catch (NativeHookException e)
{
e.printStackTrace();
}
If you are using maven, add this to your pom.xml
:
如果您使用的是 maven,请将其添加到您的pom.xml
:
<dependency>
<groupId>com.1stleg</groupId>
<artifactId>jnativehook</artifactId>
<version>2.1.0</version>
</dependency>