【问题标题】:ncurses multi colors on screenncurses 在屏幕上显示多种颜色
【发布时间】:2012-05-16 06:15:54
【问题描述】:

我想制作一个带有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


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      这是一个工作版本:

      #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 很有帮助。

      【讨论】:

      • 而不是printw,为什么不能是mvwprintw??
      • @jorgesaraiva 可能是因为不需要它?我的意思是,当然,您可以 准确指定要打印到哪个窗口以及您想要打印的位置,但是当printw("...\n") 的行为满足您的需要时,为什么还要麻烦这些呢?
      猜你喜欢
      • 1970-01-01
      • 2021-08-15
      • 1970-01-01
      • 2022-08-18
      • 1970-01-01
      • 1970-01-01
      • 2014-02-07
      • 2015-08-01
      • 1970-01-01
      相关资源
      最近更新 更多