[英]How to capture global key presses in java
I made a simple Media player in Java but I want to record global key presses like Ctrl + P to pause/resume the current music being played without the JFrame having focus but it seems that its not possible due to JVM security issues.我用 Java 制作了一个简单的媒体播放器,但我想记录全局按键,如Ctrl + P以暂停/恢复当前正在播放的音乐,而 JFrame 没有焦点,但由于 JVM 安全问题,这似乎是不可能的。
I came across JNativeHook but I want to implement my own method only for Windows.我遇到了JNativeHook,但我只想为 Windows 实现我自己的方法。 Please Suggest how to do it and where to begin ?请建议如何做以及从哪里开始?
Try JNativeHook .试试JNativeHook 。 Here is a sample that shows how to use it to capture global key presses:这是一个示例,展示了如何使用它来捕获全局按键:
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>
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 钩子:
JNA Keyboard Hook in Windows Windows 中的 JNA 键盘挂钩
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.在可移植性方面,据我所知,就响应用户输入而言,Windows dll 和 api 架构已保留在不同的操作系统版本中。 If memory serves, hooks for user input are in the user32 dll.如果没记错的话,用户输入的钩子在 user32 dll 中。 Maybe you have to jump through some hoops for a x64 bit version, but I doubt it would be that hard.也许您必须为 x64 位版本跳过一些障碍,但我怀疑这会很难。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.