ncurses屏幕上的多种颜色
我想用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();
这段代码出了什么问题?
谢谢你的每一个答案!
这是一个工作版本:
#include 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(); }
笔记:
- 你需要在
initscr()
之后调用start_color()
initscr()
来使用颜色。 - 你必须使用
COLOR_PAIR
宏将一个用init_pair
分配的颜色对init_pair
给attron
等人。 - 你不能使用颜色对0。
- 你只需要调用一次
refresh()
,并且只有你希望在那一点看到你的输出, 并且你没有调用像getch()
这样的输入函数。
这个HOWTO非常有帮助。
您需要初始化颜色并使用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"); ....