gpt4 book ai didi

c++ - 使用 WriteConsoleOutputCharacter 和 SetConsoleTextAttribute

转载 作者:可可西里 更新时间:2023-11-01 10:39:02 24 4
gpt4 key购买 nike

我正在尝试编写一个通过坐标输出的程序。我正在使用 windows.h 包含和函数 WriteConsoleOutputCharacter 将字符打印到屏幕上,但是它忽略了 SetConsoleTextAttribute 设置的颜色。有什么想法可以让它以彩色输出吗?

代码输出到控制台:

void Card::printFancy(COORD coord, bool top) const
{
paint();
LPDWORD written(0);
for (int row(0); row < CARD_WIDTH; ++row)
{
coord.Y += 1;
WriteConsoleOutputCharacter(Colorizer::getInstance().getCon(), _card[row], CARD_WIDTH, coord, written);
}
unpaint();
}

并且 paint 基本上使用适当的颜色在我的 Colorizer 类中调用一个 paint 函数Colorizer 绘制函数(由 paint() 和 unpain() 调用):

void paint(uint color)
{
SetConsoleTextAttribute(_con, color);
}

_con 是句柄,通过_con = GetStdHandle(STD_OUTPUT_HANDLE);设置

最佳答案

根据 Hans Passant 的建议在 https://stackoverflow.com/a/9275247/15485您可以将 WriteConsoleOutputCharacterWriteConsoleOutputAttribute 匹配。

enter image description here

#include <windows.h>
#include <stdio.h>

void write_symbol_in_color(HANDLE h, SHORT x, SHORT y, const char* symbol, WORD color)
{
COORD here;
here.X = x;
here.Y = y;

WORD attribute = color;
DWORD written;
::WriteConsoleOutputAttribute(h, &attribute, 1, here, &written);
::WriteConsoleOutputCharacterA(h, symbol, 1, here, &written);
}

int main()
{
HANDLE hStdOut = ::GetStdHandle(STD_OUTPUT_HANDLE);
if (hStdOut == INVALID_HANDLE_VALUE)
{
printf("Invalid handle");
return 1;
}

write_symbol_in_color(hStdOut, 0, 0, "R", FOREGROUND_RED | FOREGROUND_INTENSITY);
write_symbol_in_color(hStdOut, 1, 0, "G", FOREGROUND_GREEN | FOREGROUND_INTENSITY);
write_symbol_in_color(hStdOut, 2, 0, "B", FOREGROUND_BLUE | FOREGROUND_INTENSITY);
write_symbol_in_color(hStdOut, 3, 0, "C", FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY);
write_symbol_in_color(hStdOut, 4, 0, "M", FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY);
write_symbol_in_color(hStdOut, 5, 0, "Y", FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_INTENSITY);

return 0;
}

关于c++ - 使用 WriteConsoleOutputCharacter 和 SetConsoleTextAttribute,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9274745/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com