我想尝试制作一个类,该类将能够打印宽字符以使用特定的RGB颜色进行控制台。我知道控制台只有16个,但请先看一看。
可以通过设置正确的缓冲区来更改控制台调色板中的每种颜色,所以我写了这样的东西:
//ConsolePX #include <fcntl.h> #include <io.h> #include <Windows.h> #include <iostream> class ConsolePX { public: wchar_t source; COLORREF foreground, background; /* Set at the start ctor */ ConsolePX(wchar_t _what, COLORREF foregroundColor, COLORREF backgroundColor) { source = _what; foreground = foregroundColor; background = backgroundColor; } /* Draws wchar_t with colors to console */ void Draw() { HANDLE outH = GetStdHandle(STD_OUTPUT_HANDLE); CONSOLE_SCREEN_BUFFER_INFOEX curr, newBuff; curr.cbSize = sizeof(CONSOLE_SCREEN_BUFFER_INFOEX); GetConsoleScreenBufferInfoEx(outH, &curr); curr.srWindow.Bottom++; newBuff = curr; newBuff.ColorTable[0] = background; newBuff.ColorTable[1] = foreground; SetConsoleScreenBufferInfoEx(outH, &newBuff); SetConsoleTextAttribute(outH, 1); _setmode(_fileno(stdout), _O_U16TEXT); //Sets console mode to 16-bit unicode std::wcout << source << std::endl; _setmode(_fileno(stdout), _O_TEXT); //Restores to defaults SetConsoleTextAttribute(outH, 7); SetConsoleScreenBufferInfoEx(outH, &curr); } };
//Driver code #include "ConsolePX.h" int main() { ConsolePX(L'█', RGB(29, 219, 79), RGB(0, 0, 0)).Draw(); return 0; }
而且有效,但是问题出在ConsolePX
(恰好是SetConsoleScreenBufferInfoEx(outH, &curr)
)的最后一行。打印wchar_t
后,我将调色板恢复为默认设置。为什么会有问题呢?我注意到控制台中的每个字符都不固定为颜色,而是固定为调色板索引,因此在恢复为默认调色板后,我也恢复了wchar_t
颜色。删除该行之后,我将干扰其余的代码。有什么方法可以阻止控制台中的x,y字符以避免颜色变化?重要的是,我正在使用Visual Studio,并且您可以猜到,我正在使用Windows。
编号
您自己说过:共有16种颜色可供选择。
[当您认为自己绕过了该限制时,实际上您所做的就是更改那些颜色的“均值”,即它们映射到该控制台的RGB值。
当前调色板适用于控制台的全部内容。如果不是这样,我们将不会仅限于16种颜色。
因此,尽管您的尝试是有创造力的,但恐怕从根本上讲是行不通的。
如果要控制像这样的真实颜色,请创建一个GUI应用程序。