2012-05-07 80 views
8

我想用ncurses.h和多種顏色製作菜單。 我的意思是這樣:在屏幕上出現多種顏色

┌────────────────────┐ 
│░░░░░░░░░░░░░░░░░░░░│ <- color 1 
│▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒│ <- color 2 
└────────────────────┘ 

但是,如果使用init_pair()attron()attroff()整個畫面的顏色是一樣的,並沒有像我所預料。

initscr(); 

init_pair(0, COLOR_BLACK, COLOR_RED); 
init_pair(1, COLOR_BLACK, COLOR_GREEN); 

attron(0); 
printw("This should be printed in black with a red background!\n"); 
refresh(); 

attron(1); 
printw("And this in a green background!\n"); 
refresh()  

sleep(2); 

endwin(); 

這段代碼有什麼問題?

感謝您的每一個答案!

回答

16

這裏有一個工作版本:

#include <curses.h> 

int main(void) { 
    initscr(); 
    start_color(); 

    init_pair(1, COLOR_BLACK, COLOR_RED); 
    init_pair(2, COLOR_BLACK, COLOR_GREEN); 

    attron(COLOR_PAIR(1)); 
    printw("This should be printed in black with a red background!\n"); 

    attron(COLOR_PAIR(2)); 
    printw("And this in a green background!\n"); 
    refresh(); 

    getch(); 

    endwin(); 
} 

注:

  • 需要調用start_color()initscr()後使用的顏色。
  • 您必須使用COLOR_PAIR宏將分配有init_pair的顏色對傳遞給attron等。
  • 你不能用顏色對0
  • 你只需要調用refresh()一次,只有當你想在這一點上可以看出你的輸出,你不叫喜歡getch()輸入功能。

This HOWTO是非常有幫助的。

+1

而不是printw,爲什麼不能mvwprintw ?? –

+0

@jorgesaraiva可能是因爲沒有必要嗎?我的意思是,當然,你可以指定打印到哪個窗口以及你想要的位置,但是爲什麼當'printw(「... \ n」)'的行爲做你所需要的行爲時,爲什麼呢? –

2

您需要初始化顏色並使用COLOR_PAIR宏。

顏色對0保留爲默認顏色所以你必須開始你的索引在1

.... 

initscr(); 
start_color(); 

init_pair(1, COLOR_BLACK, COLOR_RED); 
init_pair(2, COLOR_BLACK, COLOR_GREEN); 

attron(COLOR_PAIR(1)); 
printw("This should be printed in black with a red background!\n"); 

....