C++ Win32 控制台颜色

2022-01-11 00:00:00 colors console winapi c++

我知道一点如何在 Win32 C++ 控制台中做颜色.但这并不是真正有效的.例如:

I know a bit how to do colors in Win32 C++ console. But it's not really efficient. For example:

 SYSTEM("color 01")

大大减慢您的流程.另外:

Slows down a lot on your process. Also:

 HANDLE h = GetStdHandle ( STD_OUTPUT_HANDLE );
 WORD wOldColorAttrs;
 CONSOLE_SCREEN_BUFFER_INFO csbiInfo;

 /*
  * First save the current color information
  */

 GetConsoleScreenBufferInfo(h, &csbiInfo);
 wOldColorAttrs = csbiInfo.wAttributes;

 /*
  * Set the new color information
  */

 SetConsoleTextAttribute ( h, FOREGROUND_RED );

效果很好,但颜色不多.此外,FOREGROUND_RED 是深红色.

Works great, but it doesn't have much colors. Also, FOREGROUND_RED is dark-red.

所以我想问的是,有没有像 CLR 属性 Console::ForegroundColor 这样设置的方法,所以你可以使用 ConsoleColor 枚举中的任何颜色?

So what I want to ask, isn't there a way like CLR property Console::ForegroundColor set, so you can use any color from the ConsoleColor enum?

推荐答案

控制台只支持 16 种颜色,这些颜色是由以下四个值组合而成的(我可能把灰色/深灰色弄糊涂了,但你明白了):

The console only supports 16 colors, which are created by combining the four values as follows (I might have got the gray/darkgray confused, but you get the idea):

namespace ConsoleForeground
{
  enum {
    BLACK             = 0,
    DARKBLUE          = FOREGROUND_BLUE,
    DARKGREEN         = FOREGROUND_GREEN,
    DARKCYAN          = FOREGROUND_GREEN | FOREGROUND_BLUE,
    DARKRED           = FOREGROUND_RED,
    DARKMAGENTA       = FOREGROUND_RED | FOREGROUND_BLUE,
    DARKYELLOW        = FOREGROUND_RED | FOREGROUND_GREEN,
    DARKGRAY          = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE,
    GRAY              = FOREGROUND_INTENSITY,
    BLUE              = FOREGROUND_INTENSITY | FOREGROUND_BLUE,
    GREEN             = FOREGROUND_INTENSITY | FOREGROUND_GREEN,
    CYAN              = FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_BLUE,
    RED               = FOREGROUND_INTENSITY | FOREGROUND_RED,
    MAGENTA           = FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_BLUE,
    YELLOW            = FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN,
    WHITE             = FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE,
  };
}

相关文章