douwu0335 2018-04-29 11:48
浏览 210
已采纳

在Go中捕获空格键而无需按Enter

I am looking for a lightweight and in the best case pure go implementation to capture <kbd>space</kbd> without a following <kbd>enter</kbd>.

I have seen some people using C as extern in Go or termbox. Is there really no other method of capturing every keyboard stroke?

I have already thought about opening the device directly (in Linux) and trying to read from there.

Any advice of how to do this would be great!

  • 写回答

1条回答 默认 最新

  • dongliushui2001 2018-04-29 12:11
    关注

    Without more information, it's hard to come up with a perfect example of what you're looking for. However, the basic idea is that you need to switch your terminal into raw mode, where input is passed immediately to your application. x/crypto/ssh/terminal is a popular library that provides this functionality:

    package main
    
    import (
        "fmt"
        "os"
    
        "golang.org/x/crypto/ssh/terminal"
    )
    
    func main() {
        oldState, err := terminal.MakeRaw(0)
        if err != nil {
            panic(err)
        }
        defer terminal.Restore(0, oldState)
        for {
            var oneChar [1]byte
            _, err := os.Stdin.Read(oneChar[:])
            const ETX = '\x03' // ^C
            const EOT = '\x04' // ^D
            if err != nil || oneChar[0] == ETX || oneChar[0] == EOT {
                break
            }
            if oneChar[0] == ' ' {
                fmt.Println("Space pressed!")
                break
            }
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?