0

我想编写一个程序,sound每次按下键盘上的一个按钮。(即使,如果程序不是焦点)我正在使用JNativeHook,但是当我想添加一个时Key Listener,我得到一个error因为方法。getInstance不包含在 Global Screen 中。:( 有人有想法吗?

我的代码:

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

public class jNativeHookExample implements NativeKeyListener {

    public void nativeKeyPressed(NativeKeyEvent e) {
        System.out.println(NativeKeyEvent.getKeyText(e.getKeyCode()));

        if (e.getKeyCode() == NativeKeyEvent.VC_F9) {
            //play sound;
        }
    }

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

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

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

        GlobalScreen.getInstance().addNativeKeyListener(new jNativeHookExample());
    }
}
4

1 回答 1

0

这段代码对于 jnativehook 的 1.1 版本可能是可以的。

从 2.0 版本开始,GlobalScreen该类没有getInstance()方法,addNativeKeyListener()现在是静态的,因此应该直接在以下位置调用它GlobalScreen

GlobalScreen.addNativeKeyListener(new jNativeHookExample());
于 2018-10-23T14:43:05.250 回答