// 函數會自動主力用戶輸入信息,並返回按鍵碼給調用它的函數
/* 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("\n\n");
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)
}