0

我正在尝试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

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

4

1 回答 1

1

使用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来自Lombok.

于 2018-10-07T18:21:37.533 回答