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 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥50 我撰写的python爬虫爬不了 要爬的网址有反爬机制
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等