I'm trying to use jnativehook
for global keyboard listeners but it seems like the key codes are different. For example, I want to check if ALT + I is pressed:
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...");
}
});
Checking for the ALT modifier to be pressed works as expected but checking for the I button does not work as expected:
INFO: Modifiers: 8 ALT: 8
Oct 06, 2018 2:38:44 PM com.myCompany.Main nativeKeyReleased
INFO: Key code: 23 VK_I: 73
Why is the key code 23
when I release the I button? How do I check for the I button without hard-coding those seemingly random integer constants? Java offers the KeyEvent
class for key codes but they're not applicable here, are they?
Using NativeKeyEvent.getKeyText()
and then comparing to the String button does the trick but buttons then have to be stored as Strings which is okay:
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);
}
Note: val
is from Lombok
.