Java读取Windows Key State

时间:2018-05-04 16:52:17

标签: java key keylistener jnativehook

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

我的代码:

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());
    }
}

1 个答案:

答案 0 :(得分:0)

对于jnativehook的1.1版,此代码可能是正确的。

从版本2.0开始,GlobalScreen类没有getInstance()方法,并且addNativeKeyListener()现在是静态的,因此应在GlobalScreen上直接调用它:

GlobalScreen.addNativeKeyListener(new jNativeHookExample());