jnativehook 的关键事件

KeyEvents for jnativehook

我正在尝试将 jnativehook 用于全局键盘侦听器,但键码似乎不同。例如,我想检查 ALT + I 是否被按下:

addNativeKeyListener(new NativeKeyAdapter()
{
    @Override
    public void nativeKeyReleased(NativeKeyEvent keyEvent)
    {
        val modifiers = keyEvent.getModifiers();
        val altPressed = modifiers == ALT_L_MASK;
        LOGGER.log(INFO, "Modifiers: " + modifiers + " ALT: " + ALT_L_MASK);

        if (!altPressed)
        {
            return;
        }

        val keyCode = keyEvent.getKeyCode();
        LOGGER.log(INFO, "Key code: " + keyCode + " VK_I: " + VK_I);
        if (keyCode != VK_I)
        {
            return;
        }

        LOGGER.log(INFO, "Button combination recognized...");
    }
});

检查 ALT 修改器按预期工作,但检查 I 按钮不按预期工作:

INFO: Modifiers: 8 ALT: 8
Oct 06, 2018 2:38:44 PM com.myCompany.Main nativeKeyReleased
INFO: Key code: 23 VK_I: 73

为什么我松开I键时键码是23?如何在不对那些看似随机的整数常量进行硬编码的情况下检查 I 按钮? Java 提供 KeyEvent class 键码,但它们在这里不适用,是吗?

使用 NativeKeyEvent.getKeyText() 然后与字符串按钮进行比较就可以了,但是按钮必须存储为字符串,这是可以的:

public boolean isPressed(NativeKeyEvent keyEvent)
{
    val modifiers = keyEvent.getModifiers();
    val isModifierPressed = modifiers == modifier;

    if (!isModifierPressed)
    {
        return false;
    }

    val keyCode = keyEvent.getKeyCode();
    val keyText = NativeKeyEvent.getKeyText(keyCode);
    return keyText.equals(this.keyText);
}

注:val is from Lombok.