14

I want to make a menu with ncurses.h and more than one color. I mean something like this:

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

But if I use init_pair(), attron()and attroff() the color of the whole screen is the same, and not like I've expected.

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

What's wrong with this code?

Thanks for every answer!

qwertz
  • 14,614
  • 10
  • 34
  • 46

2 Answers2

28

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.

Michael Slade
  • 13,802
  • 2
  • 39
  • 44
  • 1
    instead of printw, why can't be mvwprintw?? – jorge saraiva Nov 29 '16 at 02:26
  • 2
    @jorgesaraiva Possibly because there's no need for it? I mean, sure, you _can_ specify exactly what window to print to and where you want it, but why bother with all that when the behavior of `printw("...\n")` does what you need? – Nic Nov 30 '17 at 18:32
  • 1
    Is it possible to use `CUSTOM_COLOR` with r,g,b instead of `COLOR_RED` and if yes how should one code it? – ecjb Mar 08 '23 at 08:42
2

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");

....
Morpfh
  • 4,033
  • 18
  • 26