Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use WriteConsoleOutputAttribute function correctly

Tags:

c++

winapi

Why does the following code

  const std::string text = "str";

  HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);

  COORD coords = { 0, 0 };
  DWORD written = 0;
  WriteConsoleOutputCharacterA(stdout_handle, text.c_str(), text.size(), coords, &written);

  WORD attributes = FOREGROUND_GREEN;
  WriteConsoleOutputAttribute(stdout_handle, &attributes, text.size(), coords, &written);

results in this:

enter image description here

What am I doing wrong? How can I fix it?

like image 474
FrozenHeart Avatar asked Jul 02 '26 19:07

FrozenHeart


1 Answers

&attributes points to an array of length one, a single green attribute. But you claim the array is text.size() long. As a result, you copy random stack content to the next 2 cells. That happens to look red-on-red.

Solution:

std::vector<WORD> attributes(text.size(), FOREGROUND_GREEN);
WriteConsoleOutputAttribute(stdout_handle, &attributes[0] ...
like image 174
MSalters Avatar answered Jul 04 '26 08:07

MSalters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!