ncurses在屏幕上的多种颜色

qwe*_*rtz 9 c command-line window ncurses

我想制作一个带有ncurses.h多种颜色的菜单.我的意思是这样的:

??????????????????????
?????????????????????? <- color 1
?????????????????????? <- color 2
??????????????????????
Run Code Online (Sandbox Code Playgroud)

但是,如果使用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();
Run Code Online (Sandbox Code Playgroud)

这段代码出了什么问题?

谢谢你的每一个答案!

Mic*_*ade 21

这是一个工作版本:

#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();
}
Run Code Online (Sandbox Code Playgroud)

笔记:

  • 你需要打电话start_color()initscr()才能使用颜色.
  • 你必须使用COLOR_PAIR宏传递一个分配init_pairattronet al 的颜色对.
  • 你不能使用颜色对0.
  • 你只需要调用refresh()一次,并且只有当你希望在那一点看到你的输出时,并且你没有调用像这样的输入函数getch().

这个HOWTO非常有帮助.

  • @jorgesaraiva 可能是因为不需要它?我的意思是,当然,您_可以_指定要打印到哪个窗口以及您想要它的位置,但是当`printw("...\n")` 的行为满足您的需求时,为什么还要费心呢? (2认同)