NCURSES跳过菜单选项

时间:2015-04-11 18:39:08

标签: c++ ncurses

下面的图片显示了我在程序启动时看到的内容:

enter image description here

这是正确的,但是当我按向右箭头键选择器跳过中间菜单选项并重命名最后一个:

enter image description here

这是我的代码。要编译它,运行g++ <source_file> -lmenu -lncurses

#include <ncurses.h>
#include <menu.h>
#include <vector>
#include <string>
#include <cstdlib>

int main()
{
  // @ Initialize curses
  initscr();
  start_color();
  cbreak();
  noecho();
  curs_set(0);
  keypad(stdscr, TRUE);
  init_pair(1, COLOR_RED, COLOR_BLACK);

  // @ Setup menu
  std::vector<std::string> menuChoices;
  menuChoices.push_back(" < CREATE > ");
  menuChoices.push_back(" < VERIFY > ");
  menuChoices.push_back(" <  EXIT  > ");

  ITEM **menuItems = (ITEM **)calloc(menuChoices.size() + 1, sizeof(ITEM *));
  for (unsigned int i = 0; i < menuChoices.size(); i++)
    menuItems[i] = new_item(menuChoices[i].c_str(), menuChoices[i].c_str());
  menuItems[menuChoices.size()] = (ITEM *)NULL;
  MENU *menu = new_menu((ITEM **)menuItems);

  set_menu_mark(menu, NULL);
  set_menu_format(menu, 1, menuChoices.size());
  menu_opts_off(menu, O_SHOWDESC);

  // @ Setup window
  const int windowHeight = 6;
  const int windowWidth = 70;
  WINDOW *window = newwin(windowHeight, windowWidth, (LINES - windowHeight) / 2, (COLS - windowWidth) / 2);
  keypad(window, TRUE);
  box(window, 0, 0);
  set_menu_win(menu, window);
  set_menu_sub(menu, derwin(window, 1, 38, windowHeight - 1, (windowWidth - 38) / 2));

  // @ Post the menu
  post_menu(menu);
  wrefresh(window);

  int keyPressed;
  while ((keyPressed = wgetch(window))) {
    switch (keyPressed) {
    case KEY_RIGHT:
      menu_driver(menu, REQ_RIGHT_ITEM);
      break;
    case KEY_LEFT:
      menu_driver(menu, REQ_LEFT_ITEM);
      break;
    }
    wrefresh(window);
  }

  // @ Unpost and free all the memory taken up
  unpost_menu(menu);
  for (unsigned int i = 0; i < menuChoices.size() + 1; i++)
    free_item(menuItems[i]);
  free_menu(menu);
  endwin();
  return 0;
}

我该如何解决?

1 个答案:

答案 0 :(得分:2)

问题是程序以错误的顺序进行这些调用:

set_menu_format(menu, 1, menuChoices.size());
menu_opts_off(menu, O_SHOWDESC);

menu_opts_off调用会更改菜单项的宽度; set_menu_format调用需要知道菜单项的宽度。颠倒调用的顺序使程序按预期工作。