微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

ncurses "get_wch" 函数行为

如何解决ncurses "get_wch" 函数行为

我试图了解 ncurses 中的 get_wch 函数是如何工作的。

这是我用来在 TTY、终结器和 konsole 下测试它的一段代码

 #include <stdlib.h>
 #include <curses.h>
 #include <locale.h>
 
 int main(void)
 {
     // initialize curses
     initscr();
     setlocale(LC_ALL,"");   // Just a check to see if something change with it
     wint_t char_code;
     int key_code = get_wch(&char_code);
     char truc [20];
     sprintf(truc,"%d / %d",key_code,char_code);
     refresh();
     getch();
     endwin();
     
     printf("%d\n",KEY_CODE_YES);
     printf(truc);
     printf("\n");
     return 0;
 }

当我按下“a”或“?”这样的“经典”键时,我得到一个 char_code(我想是 UTF-8 代码)。但是当我按下 F1 或 F12 等功能键时,我得到 char_code 27 和 key_code 0,F11 除外key_code:KEY_CODE_YES, char_code:410)。

文档说:

当 get_wch、wget_wch、mvget_wch 和 mvwget_wch 函数成功报告按下功能键时,它们返回 KEY_CODE_YES。当他们成功报告一个宽字符时,他们返回 OK。

F1 到 F12 是所谓的“功能键”吗?如果我是对的,你能解释一下为什么当我按下 Fx 键时函数返回 0 作为 key_code 吗?

解决方法

您只会在 KEY_CODE_YES 设置为 true 时获得 keypad,请参阅 keypad 手册页:

The keypad option enables the keypad of the user's terminal. If enabled (bf is TRUE),the user can press a function key (such as an arrow key) and wgetch returns a single value 
representing the function key,as in KEY_LEFT. If disabled (bf is FALSE),curses does not 
treat function keys specially and the program has to interpret the escape sequences 
itself. If the keypad in the terminal can be turned on (made to transmit) and off (made to 
work locally),turning on this option causes the terminal keypad to be turned on when 
wgetch is called. The default value for keypad is false.

并且您没有从 get_wch 获得密钥代码 0 而是成功状态 OK,请参阅相关联机帮助页。

没有它,您将不得不获得多个 char_code 才能获得关键代码,例如:

     wint_t char_code;
     wint_t char_code2 = 0,char_code3 = 0;
     int key_code = get_wch(&char_code);
     if (key_code == OK) key_code = get_wch(&char_code2);
     if (key_code == OK) key_code = get_wch(&char_code3);

对于功能键,您将在 char_code (0x27) 中的转义码、在 char_code2 (0x4b) 中的功能码和在 char_code3 中的特定功能 key_code。

EDIT 正如@dratenik 所注意到的,对于 xterm/VT220+ 终端,F5-F12 功能键输出四个 char_code,因此您在获得 [ 时需要查询另一个 char_code char_code2 中的 (0x5b) 和 char_code3 中的 1 (0x31) 以获取这些功能键的特定功能键 key_code。您可以在@dratenik 提供的 this useful link 中找到可能的键码。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。