Java 系统范围的键盘快捷键

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

Java System-Wide Keyboard Shortcut

javakeyboardsystemshortcut

提问by fabiopedrosa

Is there any way or a library to get a system-wide (global) keyboard shortcut to perform an action in a Java application?

有什么方法或库可以获取系统范围(全局)键盘快捷键以在 Java 应用程序中执行操作?

采纳答案by OscarRyz

There is not, but in windows you can use this:

没有,但在 Windows 中你可以使用这个:

jintellitype

类型

Unfortunately there is nothing I'm aware of for Linux and OSX, probably that's why it doesn't come with java out of the box.

不幸的是,我对 Linux 和 OSX 一无所知,可能这就是为什么它没有开箱即用的 java。

If you find for the other platforms post it here please :)

如果您找到其他平台,请在此处发布:)

Just for couriosity, what are you doing with that?

只是出于好奇,你用它做什么?

回答by Melloware

I am the author of JIntellitype and I can tell you for a fact this must be done natively in DLL and called from Java JNI just like JIntellitype does it. This is an OS level hook that is not implemented in the JDK so libraries like JIntellitype and jxGrabKey must be used. As far as I know no one has written one for OSX yet.

我是 JIntellitype 的作者,我可以告诉你一个事实,这必须在 DLL 中本地完成,并像 JIntellitype 那样从 Java JNI 调用。这是 JDK 中未实现的操作系统级挂钩,因此必须使用 JIntellitype 和 jxGrabKey 等库。据我所知,还没有人为 OSX 写过一个。

JIntellitype is open source on Github, so if you want an idea of how it works just check out the sourcecode

JIntellitype 在 Github 上是开源的,所以如果你想了解它是如何工作的,只需查看代码

回答by dermoritz

I just found https://github.com/kwhat/jnativehook

我刚找到https://github.com/kwhat/jnativehook

Seems to be cross platform.

好像是跨平台的。

Here's their sample code for listening for key presses:

这是他们监听按键的示例代码:

import org.jnativehook.GlobalScreen;
import org.jnativehook.NativeHookException;
import org.jnativehook.keyboard.NativeKeyEvent;
import org.jnativehook.keyboard.NativeKeyListener;

public class GlobalKeyListenerExample implements NativeKeyListener {
    public void nativeKeyPressed(NativeKeyEvent e) {
        System.out.println("Key Pressed: " + NativeKeyEvent.getKeyText(e.getKeyCode()));

        if (e.getKeyCode() == NativeKeyEvent.VC_ESCAPE) {
            GlobalScreen.unregisterNativeHook();
        }
    }

    public void nativeKeyReleased(NativeKeyEvent e) {
        System.out.println("Key Released: " + NativeKeyEvent.getKeyText(e.getKeyCode()));
    }

    public void nativeKeyTyped(NativeKeyEvent e) {
        System.out.println("Key Typed: " + e.getKeyText(e.getKeyCode()));
    }

    public static void main(String[] args) {
        try {
            GlobalScreen.registerNativeHook();
        }
        catch (NativeHookException ex) {
            System.err.println("There was a problem registering the native hook.");
            System.err.println(ex.getMessage());

            System.exit(1);
        }

        GlobalScreen.addNativeKeyListener(new GlobalKeyListenerExample());
    }
}

Checking for modifiers is based on bit masks (stuff we all should know but always forget :-P):

检查修饰符基于位掩码(我们都应该知道但总是忘记:-P):

    boolean isAltPressed = (e.getModifiers() & NativeKeyEvent.ALT_MASK) != 0;
    boolean isShiftPressed = (e.getModifiers() & NativeKeyEvent.SHIFT_MASK) != 0;

This you could combine with KeyCode:

这可以与 KeyCode 结合使用:

if (e.getKeyCode() == NativeKeyEvent.VK_2 && isShiftPressed && isAltPressed){...}

This is modified example from here

这是从这里修改的示例

You should also modify the default logging behavior otherwise it will spam the console:

您还应该修改默认日志记录行为,否则它会向控制台发送垃圾邮件:

// Get the logger for "org.jnativehook" and set the level to warning.
Logger logger = Logger.getLogger(GlobalScreen.class.getPackage().getName());
logger.setLevel(Level.WARNING);

// Don't forget to disable the parent handlers.
logger.setUseParentHandlers(false);

Code example is from here

代码示例来自这里

回答by guyumu

For windows you need a keyboard hook dll. You can initialize your dll from java, which will cause it to register the listener. You'll get what you need. Check msdn for dll hooks, or keyboard hooks. One of those should set you up.

对于 Windows,您需要一个键盘钩子 dll。您可以从 java 初始化您的 dll,这将导致它注册侦听器。你会得到你需要的。检查 msdn 中的 dll 挂钩或键盘挂钩。其中之一应该设置你。

For linux I think this should be easier, but I have never done it myself.

对于 linux 我认为这应该更容易,但我自己从来没有做过。

http://ubuntuforums.org/showthread.php?t=864566

http://ubuntuforums.org/showthread.php?t=864566

Google's first result for "linux listen for global key presses" (no quotes) turns up something which I think will help you out for X11 environments

谷歌关于“linux 监听全局按键”的第一个结果(没有引号)出现了一些我认为可以帮助你解决 X11 环境的问题

OSX might just be able to use a solution close to this. But in the end, you'll probably need a dll for every platform, unless JNA could do this without issue, then the worst is done.

OSX 可能只能使用接近于此的解决方案。但最终,您可能需要为每个平台提供一个 dll,除非 JNA 可以毫无问题地做到这一点,否则最糟糕的事情已经过去了。

回答by basszero

UPDATE: I don't know if you can hook events from OUTSIDE the JVM. I think a Swing/AWT component must have focus for this to work.

更新:我不知道您是否可以从 JVM 外部挂钩事件。我认为 Swing/AWT 组件必须具有焦点才能使其工作。

You'll want to hook in the Java AWT Event Queue to be absolutely sure you can get a global (jvm wide) keypress.

您需要挂钩 Java AWT 事件队列以绝对确保您可以获得全局(jvm 范围)按键。

Use

利用

EventQueue ev = Toolkit.getSystemEventQueue();
// MyCustomEventQueue extends EventQueue and processes keyboard events in the dispatch
ev.push(new MyCustomEventQueue());

class MyEventQueue extends EventQueue
{
    protected void dispatchEvent(AWTEvent event)
    {
       // all AWTEvents can be indentified by type, KeyEvent, MouseEvent, etc
       // look for KeyEvents and match against you hotkeys / callbacks
    }
}

I think there may be other ways to accomplish global key presses with action maps. I've actually used the above mether

我认为可能还有其他方法可以通过动作地图完成全局按键操作。我实际上使用了上面的方法

回答by ivan_ivanovich_ivanoff

JDIC (Java Desktop Integration) could help
https://jdic.dev.java.net/

JDIC(Java 桌面集成)可以帮助
https://jdic.dev.java.net/

Seems to be a little unmaintained to me. I'm not sure.
If someone know more, please report!
I'm also very interested in this feature.

对我来说似乎有点无人维护。我不确定。
如果有人知道更多,请举报!
我也对这个功能很感兴趣。