C - 使用 ncurses 获取中性背景

C - Obtain neutral background with ncurses

在这个简单的程序中(用 C 编写)

#include <ncurses.h>
#include <string.h>

int main()
{
 initscr();
 printw("line 1\n");
 printw("line 2\n");
 start_color();
 init_pair(1, COLOR_RED, COLOR_BLACK);
 printw("line 3");
 getch();
 endwin();

 return 0;
}

黑色背景上的屏幕上打印了红色文本。但是当我运行程序时,背景比终端的黑色背景稍微亮一些,在Linux(Gnome终端)。

我不想设置终端的默认黑色背景颜色:我想保留终端背景并实际将 ncurses 背景设置为透明。

有办法吗?

注意:我尝试按照 this 问题中的建议将函数 use_default_colors(); 放在 start_color(); 之后,但没有用。

来自man init_pair

As an extension, ncurses allows you to set color pair 0 via the assume_default_colors routine, or to specify the use of default colors (color number -1) if you first invoke the use_default_colors routine.

所以,一般来说,如果您想使用 "default" 颜色,请使用 -1 作为颜色值,但请确保您先调用了 use_default_colors()

#include <ncurses.h>
#include <string.h>

int main()
{
 initscr();
 use_default_colors();
 printw("line 1\n");
 printw("line 2\n");
 start_color();
 init_pair(1, COLOR_RED, -1);
 printw("line 3");
 getch();
 endwin();

 return 0;
}

对于它的价值,这是一个更正的例子,从 @Pawel Veselov 的建议开始:

#include <ncurses.h>
#include <string.h>

int main(void)
{
 initscr();
 if (has_colors()) {
  use_default_colors();
  start_color();
  init_pair(1, COLOR_RED, -1);
 }
 printw("line 1\n");
 printw("line 2\n");
 attrset(COLOR_PAIR(1));
 printw("line 3");
 getch();
 endwin();

 return 0;
}

最后一行(对于合作终端)应该在终端的默认背景颜色上显示红色文本。 (迂腐地说,只有当 has_colors 为真时,才可以执行 attrset...)。

运行 黑底白字:

或白底黑字:

使用终端的默认背景。没有 use_default_colors, ncurses assumes the terminal displays white-on-black (but then you can change that assumption using assume_default_colors).