使用WriteConsoleOutputCharacter和SetConsoleTextAttribute

时间:2012-02-14 09:47:20

标签: c++ windows

我正在尝试编写一个将通过坐标输出的程序。我使用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类中的绘制函数 Colorizer绘画功能(由paint()和unpain()调用:

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

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

设置

2 个答案:

答案 0 :(得分:1)

它是WriteConsoleOutputAttribute()的对应物。一个人写一个字符但不改变属性。另一个写入属性但不更改字符。

改为使用WriteConsole()。

答案 1 :(得分:0)

根据Hans Passanthttps://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;
}