【问题标题】:How to react to keypress events in Go?如何对 Go 中的按键事件做出反应?
【发布时间】:2015-01-27 16:13:12
【问题描述】:

我在 Go 中有一个 REPL 应用程序,它应该对键盘按下事件做出反应(每个按键按下的键都有不同的操作),但 ReadString 期望在读取 os.Stdin 之前按下返回键:

import (
    "bufio"
    "os"
)

for {
    reader := bufio.NewReader(os.Stdin)
    key, _ := reader.ReadString('\n')
    deferKey(key)
}

如何响应 Go 中的按键事件?

【问题讨论】:

标签: go


【解决方案1】:

游戏引擎通常实现这种功能。它们通常也与平台无关(通常至少是 Windows、Linux、Mac OS X)。尝试例如Azul3D's keyboard library

逻辑在我的脑海中是这样的

watcher := keyboard.NewWatcher()
// Query for the map containing information about all keys
status := watcher.States()
left := status[keyboard.ArrowLeft]
if left == keyboard.Down {
    // The arrow to left is being held down
    // Do something!
}

获取当前被按下的键的列表是一个遍历映射并列出值为 Down 的键的问题。

【讨论】:

  • 我最终使用了 ncurses。但我会试试这个,因为我真的不需要 curses 库中的所有臃肿。
  • 是的,但是谁在填充该地图,必须设置状态,这个库无法满足您的需求。
【解决方案2】:

This answer 表示 similar question 指向几个选项,具体取决于您需要在哪个平台上实现它。

我个人使用过https://github.com/MarinX/keylogger
它写得很好,很容易理解。当时,我不得不编写我自己版本的这个库来听多个键盘,很容易适应这个代码。
请注意,此库仅适用于 Linux。

Example code:

import (
    "github.com/MarinX/keylogger"
    "github.com/sirupsen/logrus"
)

func main() {

    // find keyboard device, does not require a root permission
    keyboard := keylogger.FindKeyboardDevice()

    logrus.Println("Found a keyboard at", keyboard)
    // init keylogger with keyboard
    k, err := keylogger.New(keyboard)
    if err != nil {
        logrus.Error(err)
        return
    }
    defer k.Close()

    events := k.Read()

    // range of events
    for e := range events {
        switch e.Type {
        // EvKey is used to describe state changes of keyboards, buttons, or other key-like devices.
        // check the input_event.go for more events
        case keylogger.EvKey:

            // if the state of key is pressed
            if e.KeyPress() {
                logrus.Println("[event] press key ", e.KeyString())
            }

            // if the state of key is released
            if e.KeyRelease() {
                logrus.Println("[event] release key ", e.KeyString())
            }

            break
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-10
    相关资源
    最近更新 更多