如何对Go中的按键事件做出反应? [英] How to react to keypress events in Go?

查看:573
本文介绍了如何对Go中的按键事件做出反应?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a REPL app in Go that should react to keyboard press events (distinct action for each key pressed key) but ReadString expects for return key to be pressed before reading os.Stdin:

import (
    "bufio"
    "os"
)

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

我对Go中的按键事件做出了反应?

How can I react to key press events in Go?

推荐答案

游戏引擎通常实现这种功能。他们通常也是非常平台不可知论者(通常至少Windows,Linux,Mac OS X)。尝试使用 Azul3D的键盘库

Game engines commonly implement this kind of functionality. They are usually also pretty much platform agnostic (usually at least Windows, Linux, Mac OS X). Try for instance Azul3D's keyboard library.

逻辑不在我头顶,就像

The logic is off the top of my head something like

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的关键字。

Getting a list of what keys are currently being pressed down is a matter of iterating the map through and listing the keys where value was Down.

这篇关于如何对Go中的按键事件做出反应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆