Lighthouse3d.com >> GLUT Tutorial >> Pop-up Menus >> Modifying Menus
肯定会有菜单需要被修改的状况出现.GLUT运行我们修改和删除菜单项.修改菜单项的函数原型如下:
void glutChangeToMenuEntry(int entry, char *name, int value);
entry - 菜单项的索引值,介乎于1和菜单项总数之间
name - 新菜单项的名
value - 菜单项被选中时传递给回调函数的值
交换子菜单用下面这个函数:
void glutChangeToSubMenu(int entry, char *name, int menu);
entry - 菜单项的索引值,介乎于1和菜单项总数之间
name - 新菜单项的名
menu - 用于交换的菜单的索引值
下面函数用于删除菜单项.
void glutRemoveMenuItem(int entry);
entry - 菜单项的索引值,介乎于1和菜单项总数之间.
最后一样是,你可以随时用glutGet函数查询当前菜单项的数量.
下面例子演示如何更改菜单:
void processMenuEvents(int option) { red = 0.0; green = 0.0; blue = 0.0; switch (option) { case RED : red = 1.0; break; case GREEN : green = 1.0; break; case BLUE : blue = 1.0; break; case WHITE : red = 1.0; green = 1.0; blue = 1.0; break; } } void processKeys(unsigned char c, int x, int y) { int num = glutGet(GLUT_MENU_NUM_ITEMS); switch (c) { case 'a': glutChangeToMenuEntry(1,"Blue",BLUE); glutChangeToMenuEntry(3,"Red",RED); break; case 'b': glutChangeToMenuEntry(3,"Blue",BLUE); glutChangeToMenuEntry(1,"Red",RED); break; case 'c': if (num > 3) glutRemoveMenuItem(num); break; case 'd': if (num == 3) glutAddMenuEntry("White",WHITE); break; } glutSetMenu(menu); } void createGLUTMenus() { menu = glutCreateMenu(processMenuEvents); glutAddMenuEntry("Red",RED); glutAddMenuEntry("Green",GREEN); glutAddMenuEntry("Blue",BLUE); glutAddMenuEntry("White",WHITE); glutAttachMenu(GLUT_RIGHT_BUTTON); }
注意到我们以与菜单回调函数相反的形式用键盘回调函数更改了菜单.因为当菜单在使用的时候我们不能更改.菜单会在回调函数完成之前被占用,所以我们不能在回调函数内部改变菜单的结构.
之前提及到的,菜单被占用的时候,不能更改.以防万一我们需要先确认菜单是否被占用.GLUT允许我们注册一个回调函数来检测菜单是否在弹出状态.原型如下:
void glutMenuStatusFunc(void (*func)(int status, int x, int y);
func - 回调函数的名字
该函数会在main函数中调用,所以我们会把它加到main函数中.
在glutMenuStatusFunc函数中的三个参数的意思是:
status - GLUT_MENU_IN_USE或GLUT_MENU_NOT_IN_USE状态之一
x - 相对于窗体客户端区域的菜单左边坐标
y - 相对于窗体客户端区域的菜单顶部坐标
以下实例展示了当菜单被占用时设置一个标记来标识.
void processMenuStatus(int status, int x, int y) { if (status == GLUT_MENU_IN_USE) flag = 1; else flag = 0; }
现在你可以用该标记来处理键盘事件:
void processKeys(unsigned char c, int x, int y) { if (!flag) { int num = glutGet(GLUT_MENU_NUM_ITEMS); switch (c) { case 'a': glutChangeToMenuEntry(1,"Blue",BLUE); glutChangeToMenuEntry(3,"Red",RED); break; case 'b': glutChangeToMenuEntry(3,"Blue",BLUE); glutChangeToMenuEntry(1,"Red",RED); break; case 'c': if (num > 3) glutRemoveMenuItem(num); break; case 'd': if (num == 3) glutAddMenuEntry("White",WHITE); break; } } }