使用WriteConsoleOutputCharacter和SetConsoleTextAttribute

我正在试图编写一个程序,将通过坐标输出。 我正在使用windows.h include和函数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()和unpain()调用了适当的颜色Colorizer paint函数来调用paint函数:

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

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

Solutions Collecting From Web of "使用WriteConsoleOutputCharacter和SetConsoleTextAttribute"

它是WriteConsoleOutputAttribute()的对应部分。 一个写一个字符,但不改变属性。 另一个写属性,但不改变字符。

改用WriteConsole()。

正如Hans Passant在https://stackoverflow.com/a/9275247/15485中所建议的,您可以&#x5C06;WriteConsoleOutputCharacterWriteConsoleOutputAttribute匹配。

在这里输入图像说明

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