To use gowinkey
, you need to have Go installed and set
up.
Now, you can get gowinkey
by running
$ go get -u github.com/daspoet/gowinkey
and import it in your code:
import "github.com/daspoet/gowinkey"
... be sure to check out the Java version of this package.
To start listening to key events, simply run gowinkey.Listen()
. It returns a
channel on which all key events will be sent, and a function that you can call
whenever you want gowinkey
to stop listening to events.
Note that calling this function will also close the channel.
Consider the following example:
package main
import (
"fmt"
"github.com/daspoet/gowinkey"
"time"
)
func main() {
events, stopFn := gowinkey.Listen()
time.AfterFunc(time.Minute, func() {
stopFn()
})
for e := range events {
switch e.State {
case gowinkey.KeyDown:
fmt.Println("pressed", e)
case gowinkey.KeyUp:
fmt.Println("released", e)
}
}
}
To help customise the way that Listen
works, gowinkey uses Predicates. You can either supply your own, or use those that have already been created for you. You can find a collection of predefined predicates here.
Suppose we don't want to get bombarded with key events. For instance, we could only be interested in events for the keys W, A, S and D, because we want to write some basic movement for a game, or something.
We can now alter the code from above just slightly by passing the predefined predicate Selective
to Listen
. Notice that Selective
takes the keys we want to listen for and returns an appropriate predicate that will handle all the work for us.
Consider the following code snippet:
package main
import (
"fmt"
"github.com/daspoet/gowinkey"
"time"
)
func main() {
keys := []gowinkey.VirtualKey{
gowinkey.VK_W,
gowinkey.VK_A,
gowinkey.VK_S,
gowinkey.VK_D,
}
events, stopFn := gowinkey.Listen(gowinkey.Selective(keys...))
time.AfterFunc(time.Minute, func() {
stopFn()
})
for e := range events {
switch e.State {
case gowinkey.KeyDown:
fmt.Println("pressed", e)
case gowinkey.KeyUp:
fmt.Println("released", e)
}
}
}