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

问题描述

我编译了这个简单的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);
    mvwaddstr(childwin,1,4,"Move the window");
    mvwaddstr(childwin,2,"with the arrow keys");
    mvwaddstr(childwin,3,6,"or HOME/END");
    mvwaddstr(childwin,5,"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,x);
    }
 
 
    /*  Clean up after ourselves  */
 
    delwin(childwin);
    delwin(mainwin);
    endwin();
    refresh();
 
    return EXIT_SUCCESS;
}

解决方法

该示例不会重新绘制子窗口(因此似乎什么也没有发生),并且不使用cbreak(因此直到您按下 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);
     }

某些终端描述可能使用相同的字符 Control J 进行光标下移(并映射到{{1 }},而不是KEY_ENTER(请参阅source code)。排除了其他两个问题之后,您可能会发现。