开发者

NCurses getstr() with a movable cursor?

I want to read use input us开发者_如何学运维ing getstr() in NCurses. However, when I use the arrow keys, it prints keycodes instead of actually moving the cursor. How can I make it move left of right so I can edit the text before it gets passed into the buffer?


Curses does not interpret the arrow keys for input. The only thing you get is that KEY_LEFT serves as a backspace key when keypad mode is set. But luckily it is not too complicated write your own getstr replacement. The following works for me:

#include <ctype.h>
#include <string.h>
#include <ncurses.h>

static void
readline(char *buffer, int buflen)
/* Read up to buflen-1 characters into `buffer`.
 * A terminating '\0' character is added after the input.  */
{
  int old_curs = curs_set(1);
  int pos = 0;
  int len = 0;
  int x, y;

  getyx(stdscr, y, x);
  for (;;) {
    int c;

    buffer[len] = ' ';
    mvaddnstr(y, x, buffer, len+1);
    move(y, x+pos);
    c = getch();

    if (c == KEY_ENTER || c == '\n' || c == '\r') {
      break;
    } else if (isprint(c)) {
      if (pos < buflen-1) {
        memmove(buffer+pos+1, buffer+pos, len-pos);
        buffer[pos++] = c;
        len += 1;
      } else {
        beep();
      }
    } else if (c == KEY_LEFT) {
      if (pos > 0) pos -= 1; else beep();
    } else if (c == KEY_RIGHT) {
      if (pos < len) pos += 1; else beep();
    } else if (c == KEY_BACKSPACE) {
      if (pos > 0) {
        memmove(buffer+pos-1, buffer+pos, len-pos);
        pos -= 1;
        len -= 1;
      } else {
        beep();
      }
    } else if (c == KEY_DC) {
      if (pos < len) {
        memmove(buffer+pos, buffer+pos+1, len-pos-1);
        len -= 1;
      } else {
        beep();
      }
    } else {
      beep();
    }
  }
  buffer[len] = '\0';
  if (old_curs != ERR) curs_set(old_curs);
}

In order for this to work you need to have keypad move and cbreak mode on, and echo mode off:

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

I hope this helps,
Jochen

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜