gomingwkeyevent

Robotgo cannot listen to more than one event


I'm using robotgo to listen to keyboard events. I would like to add my own functions for every key pressed but I am unable to get it to trigger for more than 1 key.

So the main function looks like this:

func main() {
    go addKeyListen("l")
    go addKeyListen("k")
}

The wrapper function:

func addKeyListen(key string) {
    for {
        if ok := robotgo.AddEvent(key); ok {
            fmt.Println("Pressed "+key)
        }
    }
}

After pressing L all I am getting is Pressed l and multiple times but I can solve that with a flag. Pressing K doesn't print anything.

Tried the following:

for {
    if okA := robotgo.AddEvent("k"); okA {
        fmt.Println("Pressed k")
    }
    if okB := robotgo.AddEvent("l"); okB {
        fmt.Println("Pressed l")
    }
}

First pressing K then L, then repeating this over and over seems to trigger the events but not if I change the key press order. So if I first start with L then K, nothing happens.

PD: Testing this from windows 10 with MinGW64 version x86_64-8.1.0-posix-seh-rt_v6-rev0

Also tried different versions of MinGW from 4 onwards and same results...


Solution

  • try something like this, based on robotgo and lib used by it, tested on mac 10.14:

    package main
    
    import (
        "fmt"
        "github.com/go-vgo/robotgo"
        gohook "github.com/robotn/gohook"
    )
    
    func main() {
        eventHook := robotgo.Start()
        var e gohook.Event
        var key string
    
        for e = range eventHook {
            if e.Kind == gohook.KeyDown {
                key = string(e.Keychar)
                switch key {
                case "k":
                    fmt.Println("pressed k")
                case "l":
                    fmt.Println("pressed l")
                default:
                    fmt.Printf("pressed %s \n", key)
                }
            }
        }
    }
    

    :)