ncurses multi colors on screen

限于喜欢 提交于 2019-11-29 09:58:15

Here's a working version:

#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();
}

Notes:

  • you need to call start_color() after initscr() to use color.
  • you have to use the COLOR_PAIR macro to pass a color pair allocated with init_pair to attron et al.
  • you can't use color pair 0.
  • you only have to call refresh() once, and only if you want your output to be seen at that point, and you're not calling an input function like getch().

This HOWTO is very helpful.

You need to initialize colors and use the COLOR_PAIR macro.

Color pair 0 is reserved for default colors so you have to start your indexing at 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");

....
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!