c - ncurses 屏幕上的多种颜色

标签 c command-line window ncurses

我想用 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();

这段代码有什么问题?

感谢您的每一个回答!

最佳答案

这是一个工作版本:

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

注意事项:

  • 您需要在 initscr() 之后调用 start_color() 才能使用颜色。
  • 您必须使用 COLOR_PAIR 宏将由 init_pair 分配的颜色对传递给 attron 等。
  • 你不能使用颜色对 0。
  • 您只需调用一次 refresh(),并且仅当您希望此时可以看到您的输出时,并且您没有调用输入函数像 getch()

This HOWTO很有帮助。

关于c - ncurses 屏幕上的多种颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10487166/

相关文章:

c - Linux 内核链接

Python,使用 os.system - Python 脚本是否有办法在不等待调用完成的情况下通过它?

javascript - 我应该使用 window.load 还是 document.ready jquery

c - 如何链接具有不同结构的链表

c - glibc中printf()的跟踪代码

macos - 如何使用命令行在 Macos 上打包 Chrome 扩展程序?

C - 解析带有未知数量参数的命令行

javascript - 如何在新窗口中打开页面,而不是在同一窗口中及其新选项卡上打开页面?

c++ - 如何在 C 中使用 DirectX 9 渲染多个窗口?

cmake 错误 :Error in configuration files. 项目文件可能无效