Question

Problem

It was easy for me to figure out a method for setting console colors in C++ using windows.h and std::cout. One such method is shown here:

HANDLE stdout = GetStdHandle(STD_OUTPUT_HANDLE); //get handle of console
CONSOLE_SCREEN_BUFFER_INFO bufferInfo;
GetConsoleScreenBufferInfo(stdout, &bufferInfo); //save current color scheme
SetConsoleTextAttribute(stdout, 0x4); //change console color
std::cout << "This is red text" << std::endl; 
SetConsoleTextAttribute(stdout, bufferInfo.wAttributes); //restore old colors

Sure enough, when I run my program from a console window, the colors change as expected. The problem is, when this is run from an msbuild script, I use exec:

<Exec Command="myExecutable.exe" />

When run from the msbuild script, the colors are not affected by the program. The text still outputs in the call to std::cout, but it's just the normal console window colors.


Hypothesis

My guess is that the call to exec writes to stdout via different handle than STD_OUTPUT_HANDLE. Either that, or the msbuild exec sets its own console attributes. I've tried getting the parent console, but haven't had any luck.

Any ideas?

Était-ce utile?

La solution

The most likely thing is that MSBuild connects your executable to a pipe. When you write something to a pipe MSBuild reads it from the other end, then it may do some processing: like writing to screen, to logs, etc... The issue is that you cannot transfer colors through a pipe. In fact you can check that your stdout handle is not a console buffer using GetFileType, which will return FILE_TYPE_CHAR for a console but FILE_TYPE_PIPE if my hypothesis is correct. You also should check whether your console function calls succeeded.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top