我在我的项目中使用此代码,但是keyboard.GetSingleKey()等待按键。如何使函数不等待按键并返回nil(例如1秒后)?
package main
import (
"fmt"
"github.com/eiannone/keyboard"
)
func main() {
char, _, err := keyboard.GetSingleKey()
if (err != nil) {
panic(err)
}
fmt.Printf("You pressed: %q\r\n", char)
}
如果未按下键,则输出“未按下键”,但在另一种情况下,输出“您按下:”和键名
答案 0 :(得分:0)
func getKeyTimeout(tm time.Duration) (ch rune, err error) {
if err = keyboard.Open(); err != nil {
return
}
defer keyboard.Close()
var (
chChan = make(chan rune, 1)
errChan = make(chan error, 1)
)
go func(chChan chan<- rune, errChan chan<- error) {
ch, _, err := keyboard.GetSingleKey()
if err != nil {
errChan <- err
return
}
chChan <- ch
}(chChan, errChan)
select {
case <-time.After(tm):
return 0, err
case ch = <-chChan:
case err = <-errChan:
}
return
}
ch, err := tools.GetKey(time.Millisecond * n)
if err != nil {
panic(err)
}
if ch != rune(0) {
fmt.Printf("You pressed: %q\r\n", ch)
} else {
fmt.Printf("Key was not pressed")
}