Skip to content

Non-blocking version of GetSingleKey()#18

Open
michhernand wants to merge 3 commits intoeiannone:masterfrom
michhernand:master
Open

Non-blocking version of GetSingleKey()#18
michhernand wants to merge 3 commits intoeiannone:masterfrom
michhernand:master

Conversation

@michhernand
Copy link

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

@eiannone eiannone force-pushed the master branch 2 times, most recently from ad27fe2 to 32d709c Compare April 30, 2020 17:16
@eiannone
Copy link
Owner

Hi @mhernan88 , you should look at the latest commit 32d709c. 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...")
	}
}

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

Successfully merging this pull request may close these issues.

2 participants