【问题标题】:Simple ncurses app not reacting to arrow keys简单的 ncurses 应用程序对箭头键没有反应
【发布时间】:2023-10-25 14:29:01
【问题描述】:

我编译了这个简单的 ncurses 程序,向上向下键没有响应。 知道为什么这不起作用吗?

我使用的是 Fedora Linux 5.7.16-200.fc32.x86_64,默认的终端模拟器是 XTerm(351)。在构建 ncurses 或制作应用程序时,我没有收到任何错误或警告。

cc -o test test.c -lncurses
/* test.c */

#include <stdlib.h>
#include <stdio.h>
#include <curses.h>
 
int main(void) {
 
    WINDOW * mainwin, * childwin;
    int      ch;
 
 
    /*  Set the dimensions and initial
    position for our child window   */
 
    int      width = 23, height = 7;
    int      rows  = 25, cols   = 80;
    int      x = (cols - width)  / 2;
    int      y = (rows - height) / 2;
 
 
    /*  Initialize ncurses  */
 
    if ( (mainwin = initscr()) == NULL ) {
    fprintf(stderr, "Error initialising ncurses.\n");
    exit(EXIT_FAILURE);
    }
 
 
    /*  Switch of echoing and enable keypad (for arrow keys)  */
 
    noecho();
    keypad(mainwin, TRUE);
 
 
    /*  Make our child window, and add
    a border and some text to it.   */
 
    childwin = subwin(mainwin, height, width, y, x);
    box(childwin, 0, 0);
    mvwaddstr(childwin, 1, 4, "Move the window");
    mvwaddstr(childwin, 2, 2, "with the arrow keys");
    mvwaddstr(childwin, 3, 6, "or HOME/END");
    mvwaddstr(childwin, 5, 3, "Press 'q' to quit");
 
    refresh();
 
 
    /*  Loop until user hits 'q' to quit  */
 
    while ( (ch = getch()) != 'q' ) {
 
    switch ( ch ) {
 
    case KEY_UP:
        if ( y > 0 )
        --y;
        break;
 
    case KEY_DOWN:
        if ( y < (rows - height) )
        ++y;
        break;
 
    case KEY_LEFT:
        if ( x > 0 )
        --x;
        break;
 
    case KEY_RIGHT:
        if ( x < (cols - width) )
        ++x;
        break;
 
    case KEY_HOME:
        x = 0;
        y = 0;
        break;
 
    case KEY_END:
        x = (cols - width);
        y = (rows - height);
        break;
 
    }
 
    mvwin(childwin, y, x);
    }
 
 
    /*  Clean up after ourselves  */
 
    delwin(childwin);
    delwin(mainwin);
    endwin();
    refresh();
 
    return EXIT_SUCCESS;
}

【问题讨论】:

  • Fedora 32 有 ncurses(问题提到“构建 ncurses”)。

标签: ncurses


【解决方案1】:

该示例不会重新绘制子窗口(因此似乎什么都没有发生),也没有使用 cbreak(因此在您按下 Return之前什么都不会发生>(即,换行)。

我做了这个改变,看看它做了什么:

> diff -u foo.c.orig foo.c
--- foo.c.orig  2020-08-30 06:00:47.000000000 -0400
+++ foo.c       2020-08-30 06:02:50.583242935 -0400
@@ -29,6 +29,7 @@
  
     /*  Switch of echoing and enable keypad (for arrow keys)  */
  
+    cbreak();
     noecho();
     keypad(mainwin, TRUE);
  
@@ -85,6 +86,7 @@
     }
  
     mvwin(childwin, y, x);
+    wrefresh(childwin);
     }

某些终端描述可能使用相同的字符 ControlJ 用于光标向下(并映射到 KEY_ENTER 而不是KEY_DOWN——见source code)。在考虑了其他两个问题之后,您可能会看到这一点。

【讨论】:

  • 谢谢,我会尝试并告诉你。
  • 这些更改对我没有任何影响。 'q' 键确实退出,因此必须启用小键盘。
  • 确定 - 键盘已启用,但换行符将被特别解释。该问题未提及TERM 或正在使用的系统。
  • echo $SHELL 是 /bin/bash 而 echo $TERM 是 xterm-256color 我应该尝试另一个 TERM 吗?
  • shell 无关紧要...实际的终端模拟器是相关的。
最近更新 更多