ncurses 和 getch - 处理擦除和箭头字符

ncurses and getch - Handling erase and arrow characters

在 Linux 和 ncurses 下的 C 程序中,我需要从键盘(因此,从用户)获取字符并将它们存储到一个字符串中,这仅被认为是完整的当用户按下 Enter 时。但同时,我需要为用户显示一个屏幕回显,以便他可以看到他正在写的内容,并在必要时纠正一些拼写错误。

我的一堆代码可以工作,但无法处理擦除和箭头字符。

this问题中提供了正确store字符串的解决方案,当Backspace Del 被按下。但是可以选择什么解决方案来 显示 正确的屏幕回显,即使考虑到箭头键?

我的代码本质上是:

while(1)
{
if (getch() =! ERR)
// store the character into an array
if (getch() == 10)
// terminate the string and print it on screen
}

字符是通过getch()一个一个获取的。就像在链接的问题中一样,如果我不使用 noecho() 并按 Backspace,则会显示序列 ^? 而不是从屏幕上删除前一个字符.如果我使用 noecho(),程序应该向用户实时显示正在发生的事情。我应该在每个 while 周期重新打印字符串吗?会很麻烦。

那么,我怎样才能正确地向用户显示发生了什么?

如果您希望在用户按下 Enter 之前读取字符,您可能希望使用 getnstr 函数而不是一次读取一个字符。 getnstr 将解释擦除和杀死字符,尽管它远非一个完整的行编辑系统。

否则,您最终将不得不自己处理所有光标移动字符。这显然更灵活,但也需要更多的工作。如果你走那条路,我建议关闭回显并手动回显(非控制)字符,因为这样可以更好地控制光标位置。

如果 OP 的程序使用 keypad() function, then left-cursor (arrow) and the erase key would have the same effect. getnstr 不支持行内编辑(在行内移动光标)。 (顺便说一句,curses 的其他实现对光标键没有任何作用)。

作为支持内联编辑的程序示例,dialog is useful (it works with UTF-8). On the other hand, because it stores the responses as a plain character string, it is more complicated, say, than something explicitly written to use wget_wch

cdk 不处理 UTF-8。

ncurses 没有提供更有趣的功能,因为:

  • 该功能已在 form 库中
  • 它不符合 extension 的条件,因为人们可以在不了解库内部结构的情况下轻松开发此类各种功能。

最近 中有一个相关问题(用于阻止 I/O)(同样,dialog ).

这是我的解决方案,非常简单,不需要 noecho();

getyx( stdscr, y, x ); //get current cursor position
x-= 3; //go three position back, one for the char to erase, the other two to erase the backspace char ^? 
mvprintw( y, x, "   " ); //erase chars
move( y, x ); //get in right position for new input