尝试我的自定义菜单,我实现它是为了在处理包含多个选择操作的程序时更加方便。
菜单是可导航的(箭头:向上,向下,向左,向右),并且只需按Enter键即可进行选择,菜单方向可以垂直或水平设置,填充可以设置为一组项目(子项),子项起始位置和延迟更新。
菜单调用示例(垂直):
int response = menu("OPTIONS","[*]","->",
1,3,3,0,5,
"PROFILES","ACTIVITY","VIDEO","SOUND","GAMEPLAY");
最重要的是函数实现只需要60行代码。
菜单实现:
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <windows.h>
typedef unsigned short int usint_t;
int menu(char* name, char* prefix, char* cursor, usint_t orientation,
usint_t padding, usint_t start_pos, usint_t delay,
usint_t num_childs, ...);
int main()
{
int response = menu("OPTIONS","[*]","->",1,3,3,0,5,
"PROFILES","ACTIVITY","VIDEO","SOUND","GAMEPLAY");
switch(response)
{
case 1:
break;
case 2:
break;
}
printf("\nYour choice is: %d", response);
return 0;
}
int menu
(
char *name,
char *prefix,
char *cursor,
usint_t orient,
usint_t padding,
usint_t start_pos,
usint_t delay,
usint_t childs,
...
)
{
va_list args;
int tmp=0,pos;
char chr;
usint_t opt=start_pos;
char* format=malloc
(
(
strlen(name)+strlen(prefix)+strlen(cursor)+
3+
(2*childs)+
(padding*childs)+
childs*15
)*sizeof(char)
);
do
{
if(tmp!=0)chr=getch();
if(chr==0x48||chr==0x4B)
(opt>1&&opt!=1)?opt--:(opt=childs);
else if(chr==0x50||chr==0x4D)
(opt>=1&&opt!=childs)?opt++:(opt=1);
else {}
strcpy(format,"");
strcat(format,prefix);
strcat(format,name);
strcat(format,":");
va_start(args,childs);
for (tmp=1;tmp<=childs;tmp++)
{
(orient)?strcat(format,"\n"):0;
pos=padding;
while((pos--)>0) strcat(format," ");
if(tmp==opt)
{
strcat(format,"\b");
strcat(format,cursor);
}
strcat(format,va_arg(args,char*));
}
Sleep(delay);
system("cls");
printf(format);
va_end(args);
}while((chr=getch())!=0x0D);
return opt;
}
command
的类型必须是int
而不是char
,以便能够保存EOF
。请注意,当有人输入EOF
(例如在 Unix 上按 Ctrl-D),您的程序会在while (getchar() != '\n') ;
循环中快速执行。 - Jensdo { ... } while('0' != command);
会是一种更优雅的结构。 - guga