ncurses 多种颜色在屏幕上

问题描述 投票:0回答:2

我想做一个有

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

这段代码有什么问题?

感谢您的每一个回答!

c command-line window ncurses
2个回答
27
投票

这是一个工作版本:

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

备注:

  • 你需要在
    start_color()
    之后调用
    initscr()
    来使用颜色。
  • 您必须使用
    COLOR_PAIR
    宏将分配给
    init_pair
    的颜色对传递给
    attron
  • 你不能使用颜色对 0.
  • 你只需要调用
    refresh()
    一次,并且只有当你希望在那个时候看到你的输出时,and 你才不会调用像
    getch()
    这样的输入函数。

本 HOWTO 非常有帮助。


2
投票

您需要初始化颜色并使用 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");

....
© www.soinside.com 2019 - 2024. All rights reserved.