User pointers, hooks and other features
Adapted from Writing Programs with NCURSES, by Eric S. Raymond and Zeyd M. Ben-Halim and NCURSES Programming HOWTO, by Pradeep Padala.
The user pointer
Section titled “The user pointer”Each item, and each menu, has an associated user pointer on which you can hang application data. See mitem_userptr(3X) and menu_userptr(3X). The menu system doesn’t touch it. It works the same way as the user pointer in panels. A common use is to store the function to run when an item is chosen, for example when the user presses Enter on it.
The pointer must stay valid for as long as the item can use it. In this example every item points to the same static structure.
Example: Menu User Pointer Usage
#include <stdlib.h>#include <curses.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",};
typedef union { void (*my_func)(const char *); void *data;} MY_DATA;
static voidfunc(const char *name){}
intmain(void){ int c; int n_choices, i;
n_choices = ARRAY_SIZE(choices); if ((my_items = calloc((size_t) (n_choices + 1), perror("my_items"); return EXIT_FAILURE; }
/* Initialize curses */
/* Initialize items */ for (i = 0; i < n_choices; ++i) { static MY_DATA data = {func}; /* Set the user pointer */ }
/* Create menu */
/* Post the menu */ "Up and Down arrow keys to navigate (F1 to Exit)");
switch (c) { break; break; case 10: /* Enter */ { const MY_DATA *data;
break; } } } for (i = 0; i < n_choices; ++i)
return EXIT_SUCCESS;}Other features
Section titled “Other features”Various menu options can affect the processing and visual appearance and input processing of menus. See menu_opts(3X) for details.
It is possible to change the current item from application code; this is useful if you want to write your own navigation requests. It is also possible to explicitly set the top row of the menu display. See mitem_current(3X). If your application needs to change the menu subwindow cursor for any reason, pos_menu_cursor() will restore it to the correct location for continuing menu driver processing.
It is possible to set hooks to be called at menu initialization and wrapup time, and whenever the selected item changes. See menu_hook(3X).