// 函数会自动主力用户输入信息,并返回按键码给调用它的函数
/* menu显示函数 */
int menu(const char **menu, int start_row)
{
register int i;
static int flag = 1;
int item_count;
char *title;
int key_val;
int pointer = 0;
char item[100];
if (flag)
{
flag = 0;
pointer = 0;
}
/* 计算菜单项个数 */
item_count = 0;
while (1)
{
if (menu[item_count] != NULL)
{
item_count++;
}
else
{
break;
}
}
/* 清空屏幕 */
system("clear");
/* 进入 menu 循环 */
while (1)
{
/* 显示装饰头 */
printf("nn");
puts("\033[0;32;40m ╱◥██◣ ╭╭ ⌒╮ Have A Good Day! ^_^ ’↑’-’w’, ’↓’-’s’\033[0m");
puts("\033[0;32;40m︱田︱田田︱╰------------------------------------------------\033[0m");
/* 显示标题 */
for (i = 0; i < start_row; i++)
{
printf("n");
}
title = (char*)malloc(strlen(menu[0]) * sizeof(char) + 40 * sizeof(char));
if (title == NULL)
{
perror("malloc");
}
sprintf(title, "\033[0;31;44m%s\033[0m", menu[0]);
puts(title);
free(title);
/* 显示menu */
for (i = 1; i < item_count; i++)
{
if (i == pointer + 2)
{
char buff[200];
sprintf(buff, "\033[7;30;43m%s\033[0m", menu[i]);
puts(buff);
}
else
{
puts(menu[i]);
}
} // end for
/* 获取键盘信息,并处理 */
tcflush(0, TCIFLUSH); // 清空串口缓冲
key_val = getch();
switch (key_val)
{
case ’q’:
return -1;
case ’w’:
if (pointer > 0)
{
pointer--;
}
else
{
pointer = item_count - 4;
}
system("clear");
break;
case ’s’:
pointer++;
pointer %= (item_count - 3);
system("clear");
break;
case KEY_ENTER:
if (pointer == item_count -4)
{
pointer = -1;
}
return pointer;
default:
if (isdigit(key_val))
{
if ((key_val - ’0’ >= 0) && (key_val - ’0’ <= item_count - 5))
{
pointer = key_val - ’0’; // 字符 → 数值
return pointer;
}
}
/* 清空屏幕 */
system("clear");
pointer = 0;
printf("key_default! The key_val: %d", key_val);
} // end switch (key_val)
} // end while(1)
}