c - Ncurses 读取小键盘键和转义

标签 c linux bash ncurses getch

我正在尝试使用 ESC 退出使用 getch() 的程序。我创建了一个小程序来演示我的问题。

#include <ncurses.h>

int main(void) {

    int key = 0;

    initscr();
    noecho();
    keypad(stdscr, TRUE);

    do {

        key = getch();
        clear();
        mvprintw(0, 0, "Key = %d\n", key);
        refresh();

    } while (key != 27); 

    clear();
    refresh();
    endwin();
    return 0;

}

我正在尝试允许用户使用箭头键或小键盘(以更方便的为准)

问题出在键盘上(无论 numlock 是否打开)。当我编译并运行程序并尝试在这个简单的测试中使用数字小键盘时,只要我触摸数字小键盘,它就会退出。如果我删除 while (key != 27) (esc 为 27)条件,它会读取键并显示它们的编号。为什么当小键盘键注册为

时它会退出循环
ENTER   343
UP      120
DOWN    114
LEFT    116
RIGHT   118

非常感谢任何帮助!

最佳答案

我在 Dungeon Crawl Stone Soup 的源代码中找到了修复程序。它基本上为那些设置了键码。

{DCSS-dir}/source/libunix.cc (333)

define_key("\033Op", 1000);
define_key("\033Oq", 1001);
define_key("\033Or", 1002);
define_key("\033Os", 1003);
define_key("\033Ot", 1004);
define_key("\033Ou", 1005);
define_key("\033Ov", 1006);
define_key("\033Ow", 1007);
define_key("\033Ox", 1008);
define_key("\033Oy", 1009);

// non-arrow keypad keys (for macros)
define_key("\033OM", 1010); // Enter
define_key("\033OP", 1011); // NumLock
define_key("\033OQ", 1012); // /
define_key("\033OR", 1013); // *
define_key("\033OS", 1014); // -
define_key("\033Oj", 1015); // *
define_key("\033Ok", 1016); // +
define_key("\033Ol", 1017); // +
define_key("\033Om", 1018); // .
define_key("\033On", 1019); // .
define_key("\033Oo", 1020); // -

// variants.  Ugly curses won't allow us to return the same code...
define_key("\033[1~", 1031); // Home
define_key("\033[4~", 1034); // End
define_key("\033[E",  1040); // center arrow

关于c - Ncurses 读取小键盘键和转义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16975367/

相关文章:

python - crontab、python脚本运行失败

c - vfscanf.c 警告 : the scanf functions add several kilobytes of bloat

Linux:如何递归复制省略某些文件夹?

c - 函数中声明的局部变量不起作用

c - 文件中打印的额外字符

arrays - 使用数组项作为文件名创建文件

python - 如何使用 python 中的 evdev 从 hid 设备(条形码扫描仪)获取有效的可理解字符串

c - 用于测试命令行程序的 Shell 脚本

c - 使用 system() 执行命令时如何设置环境变量?

c - 为什么 char * 和 char 数组在比较中表现不同?