I'm relatively new to C++ and was just wondering if it is possible to have 2+ colors on one line in the console? If so, how? For example:
SetConsoleTextAttribute(hStdOut, FOREGROUND_GREEN | FOREGROUND_INTENSITY);
cout << "Green";
SetConsoleTextAttribute(hStdOut, FOREGROUND_RED | FOREGROUND_INTENSITY);
cout << "Red" << endl;
The console's foreground color for that whole line becomes red, where I want it to be green for "Green" and then red for "Red".
Don't remember how DOS is, but Commodores (what I learned to program on) used special characters... Try looking into ASCII characters?
Yes, I was able to do it with this .NET program:
static void Main(string[] args)
{
Console.ForegroundColor = ConsoleColor.White;
Console.Write("Hello, ");
Console.ForegroundColor = ConsoleColor.Gray;
Console.WriteLine("world");
Console.ReadLine();
}
I disassembled Console.ForegroundColor.set and it looks pretty equivalent to what you're doing:
Win32Native.CONSOLE_SCREEN_BUFFER_INFO bufferInfo = GetBufferInfo(false, out flag);
if (flag)
{
short attributes = (short) (bufferInfo.wAttributes & -241);
attributes = (short) (((ushort) attributes) | ((ushort) color));
Win32Native.SetConsoleTextAttribute(ConsoleOutputHandle, attributes);
}
(http://www.jinxbot.net/pub/2colorconsole.png)
As a note, I'm not sure what the overload of cout's shift operator calls, but the Windows docs say that console and text attributes do not affect the text written with low-level I/O functions such as WriteConsoleOutput or WriteConsoleOutputCharacter. Source (http://msdn.microsoft.com/en-us/library/ms682088(VS.85).aspx).
I'm not sure if that would have an impact on your program or not; just thought it was interesting. My .NET program uses WriteFile (http://msdn.microsoft.com/en-us/library/aa365747(VS.85).aspx) to write to standard output.
I think the problem was that the color changes all the text after the cursor position. I think cout does not move the cursor as it outputs text which is why I could only make one color per line.
But WriteConsole does work, thanks!