kwhat / jnativehook

Global keyboard and mouse listeners for Java.
Other
1.75k stars 348 forks source link

How to Pause and resume keystroke events #463

Open MJavoso opened 6 months ago

MJavoso commented 6 months ago

I have the next piece of code for testing:

class Listener : NativeKeyListener {
    var isAlive = true
    var flag = 0x00
    private val SUPER_MASK = 1
    private val KEY_MASK = 1 shl 1
    private val COMBINATION_MASK = SUPER_MASK or KEY_MASK

    override fun nativeKeyPressed(nativeEvent: NativeKeyEvent?) {
        nativeEvent?.let { event ->
            println("Key received")
            when(event.keyCode) {
                NativeKeyEvent.VC_O -> flag = flag or KEY_MASK
                NativeKeyEvent.VC_META -> {
                    flag = flag or SUPER_MASK
                    println("Windows")
                }

                NativeKeyEvent.VC_ESCAPE -> {
                    println("Quitando escuchador de teclas")
                    GlobalScreen.unregisterNativeHook()
                }
            }
        }
    }

    override fun nativeKeyReleased(nativeEvent: NativeKeyEvent?) {
        nativeEvent?.let { event ->
            if ((flag and COMBINATION_MASK) == COMBINATION_MASK) {
                println("Shortuct!")
            }

            when (event.keyCode) {
                NativeKeyEvent.VC_O -> flag = flag xor KEY_MASK
                NativeKeyEvent.VC_META -> flag = flag xor SUPER_MASK
            }
        }
    }
}

And here is my main method:

val listener = Listener()
    GlobalScreen.addNativeKeyListener(listener)
    GlobalScreen.registerNativeHook()
    var answer = "y"
    while (answer == "y") {
        print("Again?")
        answer= readln()
        if (answer== "y") {
            GlobalScreen.registerNativeHook()
        }
    }

    GlobalScreen.unregisterNativeHook()

    println("Exiting...")

What I am trying to achieve is to pause the keystroke logs, then answer 'y' and resume listening to keyboard. However, once I unregister the native hook, if I try to register it again, this time it won't listen to keystrokes.

Any solution?