Curses 庫提供豐富的字符屬性控制,允許在終端機上實現顏色、粗體、反白、底線、閃爍等視覺效果。核心在於 chtype 型別,它將字符碼與屬性位打包為單一整數,便於高效傳遞與組合。
/* 典型佈局(視實作而異) */
bits 0-7 : 字符碼 (A_CHARTEXT)
bits 8-15 : 屬性位 (A_ATTRIBUTES)
bits 16-23 : 顏色對索引 (A_COLOR)
bits 24-31 : 替代字符集標誌 (A_ALTCHARSET)
屬性位可用位元或 | 組合,例如 A_BOLD | A_UNDERLINE。
| 常數 | 效果 | 備註 |
|---|---|---|
A_NORMAL | 正常顯示 | 預設值,等同 0 |
A_BOLD | 加粗/高亮 | 部分終端機以亮色代替 |
A_DIM | 半亮/暗淡 | 非所有終端機支援 |
A_UNDERLINE | 底線 | |
A_BLINK | 閃爍 | 常被終端機忽略 |
A_REVERSE | 前景/背景反轉 | 最可靠的強調方式 |
A_STANDOUT | 最佳強調模式 | 通常映射為反白或粗體 |
A_ALTCHARSET | 替代字符集 | 用於繪製框線符號 |
COLOR_PAIR(n) | 顏色對 n | 需先 init_pair |
/* 設定當前窗口預設屬性,後續輸出自動套用 */
int attrset(chtype attrs);
/* 開啟指定屬性(保留原有其他屬性) */
int attron(chtype attrs);
/* 關閉指定屬性 */
int attroff(chtype attrs);
/* 便捷函數:開啟 A_STANDOUT */
int standout(void);
/* 便捷函數:關閉所有屬性 (等同 attrset(0)) */
int standend(void);
/* 窗口專用版本:wattrset, wattron, wattroff, wstandout, wstandend */
/* 從 chtype 提取純字符碼 */
#define A_CHARTEXT 0xFF
char ch = cht & A_CHARTEXT;
/* 提取屬性位 */
#define A_ATTRIBUTES 0xFF00
chtype attr = cht & A_ATTRIBUTES;
/* 提取顏色對索引 */
#define A_COLOR 0xFF0000
short pair = (cht & A_COLOR) >> 16;
#include <curses.h>
int main() {
initscr();
start_color(); // 初始化顏色子系統
use_default_colors(); // 使用終端機預設色
init_pair(1, COLOR_WHITE, COLOR_BLUE); // 標題列
init_pair(2, COLOR_YELLOW, COLOR_BLACK); // 選項
init_pair(3, COLOR_BLACK, COLOR_CYAN); // 選中項
attron(COLOR_PAIR(1) | A_BOLD);
mvprintw(0, 0, " 系統管理選單 ");
attroff(COLOR_PAIR(1) | A_BOLD);
const char *items[] = {"用戶管理", "網路設定", "日誌查看", "退出"};
int highlight = 0, ch;
while (1) {
for (int i = 0; i < 4; i++) {
move(i+2, 4);
if (i == highlight) attron(COLOR_PAIR(3) | A_REVERSE);
else attron(COLOR_PAIR(2));
printw(" %s ", items[i]);
attroff(A_REVERSE | COLOR_PAIR(2) | COLOR_PAIR(3));
}
refresh();
ch = getch();
if (ch == KEY_UP) highlight = (highlight + 3) % 4;
else if (ch == KEY_DOWN) highlight = (highlight + 1) % 4;
else if (ch == '\n') break;
}
endwin();
printf("選擇了: %s\n", items[highlight]);
return 0;
}
start_color() 才能使用 COLOR_PAIR,否則回傳 0。COLOR_PAIRS 通常為 256,超出會失效。attrset 會完全替換當前屬性,非疊加;疊加請用 attron/attroff。WINDOW* 維護獨立屬性狀態。參考來源:「暗日」博客 原文連結