You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Added support for media keys as well as other keys.
Use a map for key lookup internally, for simplicity.
Example
import"github.com/17xande/keylogger"funcmain() {
device:=flag.String("device", "keyboard", "device name to listen to")
flag.Parse()
// Wait for Ctrl + C to exitc:=make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
ctx, cancel:=context.WithCancel(context.Background())
deferfunc() {
cancel()
close(c)
}()
golistenLoop(ctx, *device)
fmt.Println("listening: ")
<-ccancel()
}
funclistenLoop(ctx context.Context, devicestring) {
// We can use an infinite loop to start listening again if something// goes wrong, eg: a device is disconnected.for {
iferr:=Listen(ctx, device); err!=nil {
fmt.Println("error listening to device:", err)
time.Sleep(1*time.Second)
}
}
}
// Listen to all the Input Devices supplied. This blocks while listening.// Return an error if there is a problem, or if one of the devices disconnects.funcListen(ctx context.Context, devstring) error {
vare keylogger.InputEventvarerrerrorvaropenboolds:=keylogger.ScanDevices(dev)
iflen(ds) <=0 {
returnfmt.Errorf("device '%s' not found", dev)
}
for_, d:=rangeds {
fmt.Printf("Listening to device %s\n", d.Name)
}
cie:=make(chan keylogger.InputEvent)
cer:=make(chanerror)
c, cancel:=context.WithCancel(ctx)
deferfunc() {
// Cancel all the goroutines reading the device files.cancel()
// Close opened channels.close(cie)
close(cer)
}()
// Star reading each found device.kl.Read(c, cie, cer)
for {
select {
// Listen for device events.casee, open=<-cie:
if!open {
returnerrors.New("event channel closed")
}
// Handle device event.fmt.Printf("%2x\t%s\n", e.Type, e.KeyString())
// Listen for reading errors.caseerr, open=<-cer:
if!open {
returnerrors.New("error channel closed")
}
returnerr
}
}
}