简单的 ncurses 应用程序对箭头键没有反应

Simple ncurses app not reacting to arrow keys

我编译了这个简单的 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;
}

该示例没有重绘 child-window(因此似乎没有任何反应),也没有使用 cbreak(因此在您按下 [=22 之前没有任何反应) =]Return(即newline)。

我进行了此更改以查看它的作用:

> 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 cursor-down(并映射到 KEY_ENTER 而不是 KEY_DOWN——参见 source code)。在考虑到其他两个问题后,您可能会看到这一点。