【问题标题】:How can I get keyboard input data in Go?如何在 Go 中获取键盘输入数据?
【发布时间】:2022-01-22 14:46:08
【问题描述】:

我希望能够判断用户是否在 Go 的键盘上按下了诸如 Ctrl+[something] 或 Esc 之类的东西。该程序在终端内的 Linux 环境中运行。

【问题讨论】:

    标签: linux go terminal keyboard raw


    【解决方案1】:
    1. 如果您只想简单地读取字符串或字节,您可以这样做
    in := bufio.NewScanner(os.Stdin)
    data := in.Bytes()
    
    1. 如果要捕获系统信号量,可以通过注册信号量监视器来获取
    signal.Notify(os.Interrupt, os.Kill) // os.Interrupt=0x2 os.Kill=0x9
    
    1. 通过按键获取 ASCII 码(跨平台)(使用 github.com/nsf/termbox-go)
    import (
        "fmt"
        term "github.com/nsf/termbox-go"
    )
    
    func main() {
        err := term.Init()
        if err != nil {
            panic(err)
        }
        defer term.Close()
    
        for {
            switch ev := term.PollEvent(); ev.Type {
            case term.EventKey:
                switch ev.Key {
                case term.KeyEsc:
                    term.Sync()
                    fmt.Println("ESC pressed")
                case term.KeyF1:
                    term.Sync()
                    fmt.Println("F1 pressed")
                case term.KeyInsert:
                    term.Sync()
                    fmt.Println("Insert pressed")
                case term.KeyDelete:
                    term.Sync()
                    fmt.Println("Delete pressed")
                case term.KeyHome:
                    term.Sync()
                    fmt.Println("Home pressed")
                case term.KeyEnd:
                    term.Sync()
                    fmt.Println("End pressed")
                case term.KeyPgup:
                    term.Sync()
                case term.KeyArrowRight:
                    term.Sync()
                    fmt.Println("Arrow Right pressed")
                case term.KeySpace:
                    term.Sync()
                    fmt.Println("Space pressed")
                case term.KeyBackspace:
                    term.Sync()
                    fmt.Println("Backspace pressed")
                case term.KeyEnter:
                    term.Sync()
                    fmt.Println("Enter pressed")
                case term.KeyTab:
                    term.Sync()
                    fmt.Println("Tab pressed")
    
                default:
                    term.Sync()
                    fmt.Println("ASCII : ", ev.Ch)
    
                }
            case term.EventError:
                panic(ev.Err)
            }
        }
    }
    
    1. 读取单个字符
    consoleReader := bufio.NewReaderSize(os.Stdin, 1)
    input, _ := consoleReader.ReadByte()
    ascii := input
    
    // ESC = 27 and Ctrl-C = 3
    if ascii == 27 || ascii == 3 {
        fmt.Println("Exiting...")
        os.Exit(0)
    }
    
    fmt.Println("ASCII : ", ascii)
    

    Golang reading from stdin
    Get ASCII code from a key press

    【讨论】:

      猜你喜欢
      • 2022-01-22
      相关资源
      最近更新 更多