Java 中的事件侦听器而应用程序没有焦点?(全局按键检测)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/800747/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 13:52:03  来源:igfitidea点击:

Event listener in Java without app having focus? (Global keypress detection)

javajava-native-interfacelistenerkeylistener

提问by Ross

I've been searching for a while and everybody seems to think this is not possible using just Java, so I'll give SO a shot ;)

我已经搜索了一段时间,每个人似乎都认为仅使用 Java 是不可能的,所以我会试一试;)

Is there any way to have my Java application listen for events (key events in particular) while another unrelated application has window focus? In my situation, I'm looking to detect when the user has pressed the 'Pause' key on the keyboard even though my Java application does not have focus.

有没有办法让我的 Java 应用程序在另一个不相关的应用程序具有窗口焦点时侦听事件(特别是关键事件)?在我的情况下,即使我的 Java 应用程序没有焦点,我也希望检测用户何时按下了键盘上的“暂停”键。

I've heard some people mention that the only way is to write some C code and use JNI. Just curious if anybody knew of a way to avoid that? Or, if not, at least a really nice tutorial on the c/JNI stuff?

我听说有人提到唯一的方法是编写一些 C 代码并使用 JNI。只是好奇是否有人知道避免这种情况的方法?或者,如果没有,至少有一个关于 c/JNI 内容的非常好的教程?

Thanks

谢谢

采纳答案by Lawrence Dol

It's my understanding that this can't be done. At a fundamental level, the JVM only generates events for O/S events it receives, and it only receives O/S input events when it has focus.

我的理解是这是不可能的。从根本上讲,JVM 只为它接收到的 O/S 事件生成事件,并且只有在它有焦点时才接收 O/S 输入事件。

I am sure you coulduse JNI to trigger the O/S to generate events for all input, but that would be very O/S dependent.

我确信您可以使用 JNI 来触发 O/S 为所有输入生成事件,但这将非常依赖于 O/S。

回答by Jen S.

Here is the best answer I've found:

这是我找到的最佳答案:

" There is a library to handle native keyboard and mouse control: https://github.com/kwhat/jnativehook) "

" 有一个库来处理原生键盘和鼠标控制:https: //github.com/kwhat/jnativehook) "

回答by Dave

I'm not aware of any way to get around that either. I did find this link on Java's forumswith a good example of how to setup the JNI stuff and make a global keyboard handler (too much to add here). It's a little dated (2005), but the example looks thorough enough to get you started.

我也不知道有什么方法可以解决这个问题。我确实在 Java 的论坛上找到了这个链接,里面有一个很好的例子,说明了如何设置 JNI 内容并制作全局键盘处理程序(这里添加太多)。它有点过时(2005 年),但该示例看起来足以让您入门。