Registering Multi-Key Presses with JNativeHook

You need to listen for each individual key push and release event for the combination required and set some kind of flag as each of the keys is depressed. If after 1 of the desired keys is pressed, and the flag condition is met, then you can do whatever you need to do when those keys are pressed together. There is no way to get a single event for two keys without creating a custom keyboard driver. If you goal is to suppress the W and A key events until both are press, look at the unsupported consuming events section of the docs. Note that event suppression is only available on Windows and OS X targets and the suppressed events will not be delivered to other applications.

Its not the prettiest example, but it should do what you are look for.

private short hotKeyFlag = 0x00;
private static final short MASK_A = 1 << 0;
private static final short MASK_W = 1 << 1;

...
@Override
public void nativeKeyPressed(NativeKeyEvent e) {
    if (e.getKeyCode() == NativeKeyEvent.VC_ESCAPE) {
        GlobalScreen.unregisterNativeHook();
    }
    else if (e.getKeyCode() == NativeKeyEvent.VK_A) {
        hotKeyFlag &= MASK_A;
    }
    else if (e.getKeyCode() == NativeKeyEvent.VK_W) {
        hotKeyFlag &= MASK_W;
    }

    // Check the mask and do work.
    if (hotKeyFlag == MASK_A & MASK_W) {
        // Fire Shortcut.
    }
}

@Override
public void nativeKeyReleased(NativeKeyEvent e) {
    if (e.getKeyCode() == NativeKeyEvent.VK_A) {
        hotKeyFlag ^= MASK_A;
    }
    else if (e.getKeyCode() == NativeKeyEvent.VK_W) {
        hotKeyFlag ^= MASK_W;
    }
}

This is my answer:-

private boolean a = false, w = false;

@Override
public void nativeKeyPressed(NativeKeyEvent e) {
    if (e.getKeyCode() == NativeKeyEvent.VC_A) {
        a = true;
        if (w) {
            System.out.println("W+A");
        } else {//remove this else only for testing
            System.out.println("Only A");
        }
    } else if (e.getKeyCode() == NativeKeyEvent.VC_W) {
        w = true;
        if (a) {
            System.out.println("A+W");
        } else {//remove this else only for testing
            System.out.println("Only W");
        }
    }
}

@Override
public void nativeKeyReleased(NativeKeyEvent e) {
    if (e.getKeyCode() == NativeKeyEvent.VC_A) {
        a = false;
    } else if (e.getKeyCode() == NativeKeyEvent.VC_W) {
        w = false;
    }
}

@Override
public void nativeKeyTyped(NativeKeyEvent e) {
    //System.out.println("Key Typed: " + e.getKeyText(e.getKeyCode()));
}

Tags:

Java