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

NCurses 進階:中文支援、視窗與子視窗管理、邊框繪製實戰

     編輯:關於C

中文支援關鍵

  • 連結 ncursesw(寬字元版本)而非 ncurses
  • 程式開頭呼叫 setlocale(LC_ALL, "")
  • 編譯:gcc -lncursesw 1.c -o mytest

中文顯示範例

#include 
#include 
#include 

int main() {
    setlocale(LC_ALL, "");
    initscr();
    box(stdscr, ACS_VLINE, ACS_HLINE);
    
    if (!has_colors() || start_color() == ERR) {
        endwin(); printf("終端不支援色彩\n"); return 0;
    }
    
    init_pair(1, COLOR_GREEN, COLOR_BLACK);
    init_pair(2, COLOR_RED, COLOR_BLACK);
    init_pair(3, COLOR_WHITE, COLOR_BLUE);
    
    for (int i = 1; i <= 3; i++) {
        attron(COLOR_PAIR(i));
        move(i, 10);
        printw("hello,世界%d", i);  // 中文測試
    }
    for (int i = 1; i <= 3; i++) {
        attron(COLOR_PAIR(i) | A_UNDERLINE);
        move(i + 5, 10);
        printw("hello,世界:%d", i);
    }
    
    refresh(); getch(); endwin();
    return 0;
}

中文顯示效果

視窗與子視窗

核心函數

  • newwin(nlines, ncols, begin_y, begin_x):建立新視窗
  • derwin(orig, nlines, ncols, begin_y, begin_x):建立子視窗(相對父視窗位置)
  • subwin(orig, nlines, ncols, begin_y, begin_x):建立子視窗(相對根視窗絕對位置)
  • wrefresh(win):刷新指定視窗
  • touchwin(win):切換當前視窗
  • delwin(win):刪除視窗釋放資源

視窗操作範例

#include 
#include 

int main() {
    setlocale(LC_ALL, "");
    WINDOW *win1, *win2, *subwin;
    initscr();
    
    win1 = newwin(15, 50, 1, 1);
    box(win1, ACS_VLINE, ACS_HLINE);
    mvwprintw(win1, 1, 1, "WIN1");
    mvwprintw(win1, 2, 1, "您好,很高興認識您");
    
    win2 = newwin(10, 40, 10, 30);
    box(win2, ACS_VLINE, ACS_HLINE);
    mvwprintw(win2, 1, 1, "WIN2");
    mvwprintw(win2, 2, 1, "您好,很高興認識您");
    
    subwin = derwin(win2, 3, 20, 3, 5);  // win2 的子視窗
    box(subwin, ACS_VLINE, ACS_HLINE);
    mvwprintw(subwin, 1, 5, "按任意鍵退出");
    
    refresh();
    wrefresh(win1);
    wrefresh(win2);
    
    touchwin(win1); wrefresh(win1); getch();  // 先顯示 win1
    touchwin(win2);                           // 再顯示 win2
    
    // 使用 doupdate 批次刷新
    wnoutrefresh(win2);
    wnoutrefresh(subwin);
    doupdate();
    getch();
    
    delwin(win1); delwin(subwin); delwin(win2);
    endwin();
    return 0;
}

編譯與結果

gcc -lncursesw 1.c -o mytest
./mytest

視窗與子視窗效果

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