Valhalla Legends Archive

Programming => General Programming => C/C++ Programming => Topic started by: iNsaNe on September 18, 2008, 09:48 PM

Title: SetConsoleTextAttribute
Post by: iNsaNe on September 18, 2008, 09:48 PM
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".
Title: Re: SetConsoleTextAttribute
Post by: Barabajagal on September 18, 2008, 11:31 PM
Don't remember how DOS is, but Commodores (what I learned to program on) used special characters... Try looking into ASCII characters?
Title: Re: SetConsoleTextAttribute
Post by: MyndFyre on September 19, 2008, 01:36 PM
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)
Title: Re: SetConsoleTextAttribute
Post by: MyndFyre on September 19, 2008, 02:12 PM
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.
Title: Re: SetConsoleTextAttribute
Post by: iNsaNe on September 20, 2008, 12:05 PM
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!