cipher
cipher

Reputation: 2484

How can I use colors in my console app (C)?

I am running C in Code:Blocks IDE with the compiler GNU GCC. And I want to use colorful string output in my console application. The OS I am on is Windows

Previously, I used Borland C. So, using textcolor() textbackground() and cprintf() were fine. But these function does not seem to work on Code:Blocks IDE with GNU GCC Compiler wrapped with it.

What should I do to print colored texts now?

Upvotes: 1

Views: 3499

Answers (1)

Mike
Mike

Reputation: 49403

Color in a terminal is built into standard Windows, and it's pretty easy. You want the SetConsoleTextAttribute() function, here's a very quick example:

#include <stdio.h>
#include <Windows.h>
#include <string.h>

void main()
{
    printf("Hello\n");  // Print white text on black output
    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_RED);
    printf("Hello Again!\n");  // Print Red text on black output
    getchar(); // Pause the program to admire the colors
}

For further highlighting you can also change the back ground, you can OR (|) together flags to get different colors and different back/fore grounds.

So if you wanted to do red text on a green back ground (for some reason) you could do:

FOREGROUND_RED | BACKGROUND_GREEN

enter image description here

You can also mix colors by OR'ing more than one foreground or background color for example:

FOREGROUND_GREEN | FOREGROUND_BLUE

Will give you a blue-green colored text.

Upvotes: 1

Related Questions