2012-05-07 78 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"); 

....