我正在尝试将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类,但是它们在这里不适用,对吗?

最佳答案

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

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

关于java - jnativehook的KeyEvent,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52679271/

10-12 05:52