Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to Pause and resume keystroke events #463

Open
MJavoso opened this issue May 17, 2024 · 0 comments
Open

How to Pause and resume keystroke events #463

MJavoso opened this issue May 17, 2024 · 0 comments

Comments

@MJavoso
Copy link

MJavoso commented May 17, 2024

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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant