Skip to content

Menu colors and unselectable items

Adapted from Writing Programs with NCURSES, by Eric S. Raymond and Zeyd M. Ben-Halim and NCURSES Programming HOWTO, by Pradeep Padala.

Color makes a menu look like the ones in text-mode DOS games. The HOWTO pointed to a collection of them, whose site is gone; the link is to the Internet Archive’s 2001 copy. The functions set_menu_fore() and set_menu_back() change the attribute of the selected item and of the unselected items. The names are misleading: they don’t change the menu’s foreground or background, which would have been useless.

The function set_menu_grey() sets the display attribute for the non-selectable items in the menu. That brings us to the one and only item option, O_SELECTABLE. Turn it off with set_item_opts() or item_opts_off() and the item can’t be selected, like a grayed item in a graphical menu. It is the only option so far defined for items, but it is good practice to code as though other option bits might be on.

Example: Menu Options example

#include <stdlib.h>
#include <menu.h>
#define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
#define CTRLD 4
const char *choices[] = {
"Choice 1",
"Choice 2",
"Choice 3",
"Choice 4",
"Choice 5",
"Choice 6",
"Choice 7",
"Exit",
};
int
main(void)
{
ITEM **my_items;
int c;
MENU *my_menu;
int n_choices, i;
/* Initialize items */
n_choices = ARRAY_SIZE(choices);
if ((my_items = calloc((size_t) (n_choices + 1),
sizeof(ITEM *))) == NULL) {
perror("my_items");
return EXIT_FAILURE;
}
/* Initialize curses */
cbreak();
noecho();
for (i = 0; i < n_choices; ++i) {
my_items[i] = new_item(choices[i], choices[i]);
}
my_items[n_choices] = (ITEM *) NULL;
item_opts_off(my_items[3], O_SELECTABLE);
item_opts_off(my_items[6], O_SELECTABLE);
/* Create menu */
my_menu = new_menu((ITEM **) my_items);
/* Set fore ground and back ground of the menu */
set_menu_back(my_menu, COLOR_PAIR(2));
set_menu_grey(my_menu, COLOR_PAIR(3));
/* Post the menu */
mvprintw(LINES - 3, 0, "Press <ENTER> to see the option selected");
mvprintw(LINES - 2, 0,
"Up and Down arrow keys to navigate (F1 to Exit)");
post_menu(my_menu);
while ((c = getch()) != KEY_F(1)) {
switch (c) {
case KEY_DOWN:
break;
case KEY_UP:
break;
case 10: /* Enter */
move(20, 0);
mvprintw(20, 0, "Item selected is : %s",
item_name(current_item(my_menu)));
pos_menu_cursor(my_menu);
break;
}
}
unpost_menu(my_menu);
free_menu(my_menu);
for (i = 0; i < n_choices; ++i)
free_item(my_items[i]);
endwin();
return EXIT_SUCCESS;
}