首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

Curses 庫字符屬性函數完整手冊

     編輯:關於C語言

概述

Curses 庫提供豐富的字符屬性控制,允許在終端機上實現顏色、粗體、反白、底線、閃爍等視覺效果。核心在於 chtype 型別,它將字符碼與屬性位打包為單一整數,便於高效傳遞與組合。

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;
}

常見坑點提醒

  1. 必須呼叫 start_color() 才能使用 COLOR_PAIR,否則回傳 0。
  2. 顏色對數量有限:COLOR_PAIRS 通常為 256,超出會失效。
  3. attrset 會完全替換當前屬性,非疊加;疊加請用 attron/attroff。
  4. 屬性不跨窗口繼承:每個 WINDOW* 維護獨立屬性狀態。
  5. 終端機能力差異大:發佈前請在目標終端機(xterm, vt100, linux console, Windows Terminal 等)實測。

參考來源:「暗日」博客 原文連結

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved