cwindowsterminalcolorsconsole

Colored Text Windows Command Line


Recently I'm messing around with colors in the terminal.

I'm using a sample program from here to test this out in different consoles.

In the Windows Terminal from the Microsoft Store, you can see colors:

colors

Below is the exact same program, but in cmd.exe in which you can't see the colors.

No colors

In the same exact console however, when I run the command gcc I do get additional colors (white and red, in fact):

gcc

Now my question is, what does gcc do differently, to still be able to print colored text? I can't find any other way to get colored text on the console than written on the linked site above.


Solution

  • This question can help you:

    This is the list for functions you needed (in this example we use red in green):

        HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
        CONSOLE_SCREEN_BUFFER_INFO consoleBuffer;
        GetConsoleScreenBufferInfo (hStdOut, &consoleBuffer);
        const char *string = "AABBCCDDEEFFGG";
        int length = strlen(string);
        DWORD written;
        WriteConsoleOutputAttribute(hStdOut, (WORD*)(FOREGROUND_RED | BACKGROUND_GREEN), length, consoleBuffer.dwCursorPosition, &written);
        WriteConsoleOutputCharacter(hStdOut, string, length, consoleBuffer.dwCursorPosition, &written);
    
        HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
        CONSOLE_SCREEN_BUFFER_INFO consoleBuffer;
        const char* string = "AABBCCDDEEFFGG";
        int length = strlen(string);
        DWORD written;
        GetConsoleScreenBufferInfo(hStdOut, &consoleBuffer);
        SetConsoleTextAttribute(hStdOut, FOREGROUND_RED | BACKGROUND_GREEN);
        WriteConsoleOutputCharacter(hStdOut, string, length, consoleBuffer.dwCursorPosition, &written);
        SetConsoleTextAttribute(hStdOut, FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED | 0);
    

    Note: You can use WriteConsole() instead of using WriteConsoleOutputCharacter() function. Don't forget to restore the mode!