keyboard icon indicating copy to clipboard operation
keyboard copied to clipboard

Non-blocking version of GetSingleKey()

Open michhernand opened this issue 5 years ago • 1 comments

A non-blocking version of GetSingleKey(). This version can be used in loops to capture keys while not blocking other processes.

michhernand avatar Mar 31 '20 19:03 michhernand

Hi @mhernan88 , you should look at the latest commit 32d709cec0bda67cd16653ef4175556f5f79cacd. I have added a new function GetKeys(), which returns a channel with the keystroke events. You can get the keystrokes in a non blocking way with the following code:

keysEvents, err := keyboard.GetKeys(10)
if err != nil {
	panic(err)
}
defer func() {
	_ = keyboard.Close()
}()

fmt.Println("Press ESC to quit")
fmt.Println("Starting loop...")
forLoop:
for {
	select {
	case event := <-keysEvents:	
		if event.Err != nil {
			panic(event.Err)
		}
		fmt.Printf("You pressed: rune %q, key %X\r\n", event.Rune, event.Key)
		if event.Key == keyboard.KeyEsc {
			fmt.Println("Exiting loop!")
			break forLoop
		}
		break
	default:
		time.Sleep(time.Second * 1)
		fmt.Println("Continuing loop...")
	}
}

eiannone avatar Apr 30 '20 17:04 eiannone