douhandie6615 2016-04-17 17:02
浏览 176
已采纳

在Golang和ncurses中仅接受字母数字

So, I'm teaching myself some Golang by making a simple resource management game with ncurses. I'm using this library to connect Golang to ncurses.

I've made a simple text input panel that takes in one character at a time, displays it, and then adds it to a string composing the user's response. Here's what it looks like:

// Accept characters, printing them until end
ch := window.GetChar()
kstr := gc.KeyString(ch)
response := ""
cur := 0
for kstr != "enter" {
    // Diagnostic print to get key code of current character 
    window.Move(0,0)
    window.ClearToEOL()
    window.MovePrint(0, 0, ch)

    // If its a backspace or delete, remove a character
    // Otherwise as long as its a regular character add it
    if ((ch == 127 || ch == 8) && cur != 0){
        cur--
        response = response[:len(response)-1] 
        window.MovePrint(y, (x + cur), " ")
    } else if (ch >= 33 && ch <= 122  && cur <= 52) {
        window.MovePrint(y, (x + cur), kstr)
        response = response + kstr
        cur++
    }

    // Get next character
    ch = window.GetChar()
    kstr = gc.KeyString(ch)
}

However, the arrow and function keys seem to be coming up as keycodes already associated with the normal a-zA-Z characters. For example, right-arrow comes up as 67 and F1 as 80. Any ideas what I'm doing wrong here, or if there's a better approach to taking in alphanumerics through ncurses? I'd like to avoid ncurses fields and classes as much as possible, because the point here is to learn Golang, not ncurses. Thanks!

  • 写回答

1条回答 默认 最新

  • duanmie9741 2016-04-17 18:51
    关注

    If you do not enable the keypad mode, (n)curses will return the individual bytes which make up a special key.

    To fix, add this to your program's initialization:

    stdscr.Keypad(true)   // allow keypad input
    

    which will return special keys such as right-arrow as values above 255. goncurses has symbols defined for those, e.g., KEY_RIGHT.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?