Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ncurses multi colors on screen

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!

like image 756
qwertz Avatar asked May 07 '12 18:05

qwertz


People also ask

How many Colors does ncurses support?

Why does ncurses support only eight colors? But why only eight colors, and why these particular colors? At least with the Linux console, if you're running on a PC, the color range's origins are with the PC hardware.

How do you use colors in ncurses?

To establish a color pair, use init_pair() to define a foreground and background color, and associate it to an index number. The general syntax is: init_pair(index, foreground, background); Consoles support only eight basic colors: black, red, green, yellow, blue, magenta, cyan and white.

Does ncurses work on Windows?

In ncurses, "windows" are a means to divide the screen into logical areas. Once you define a window, you don't need to track its location on the screen; you just draw to your window using a set of ncurses functions.


1 Answers

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.

like image 160
Michael Slade Avatar answered Oct 13 '22 22:10

Michael Slade