Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C color text in terminal applications in windows

I know "textcolor();" is for C++ and i've seen methods for unix... but is there way for windows also?

#include <stdio.h>
int main()
{
    printf("\ntest - C programming text color!");
    printf("\n--------------------------------");
    printf("\n\n\t\t-BREAK-\n\n");
    textcolor(15);
    printf("WHITE\n");
    textcolor(0);
    printf("BLACK\n");
    textcolor(4);
    printf("RED\n");
    textcolor(1);
    printf("BLUE\n");
    textcolor(2);
    printf("GREEN\n");
    textcolor(5);
    printf("MAGENTA\n");
    textcolor(14);
    printf("YELLOW\n");
    textcolor(3);
    printf("CYAN\n");
    textcolor(7);
    printf("LIGHT GRAY\n");
}

I can't find any anything on the net... let's hope the good people from stack overflow can help :D

C please, not C++

like image 383
Joe DF Avatar asked Feb 08 '12 23:02

Joe DF


People also ask

Do ANSI colors work on Windows?

ANSI colors are available by default in Windows version 1909 or newer. See below for older versions.

How do I change text color in CPP?

If You want to change the Text color in C++ language There are many ways. In the console, you can change the properties of output. click this icon of the console and go to properties and change color. The second way is calling the system colors.

How do you change the color of a terminal in C++?

Use SetConsoleTextAttribute() Method to Change Console Color in C++ SetConsoleTextAttribute is the Windows API method to set output text colors using different parameters. This function sets the attributes of characters written to the console screen buffer by the WriteFile or WriteConsole functions.


1 Answers

Since you want a C and Windows specific solution, I'd recommend using the SetConsoleTextAttribute() function in the Win32 API. You'll need to grab a handle to the console, and then pass it with the appropriate attributes.

As a simple example:

/* Change console text color, then restore it back to normal. */
#include <stdio.h>
#include <windows.h>

int main() {
    HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
    CONSOLE_SCREEN_BUFFER_INFO consoleInfo;
    WORD saved_attributes;

    /* Save current attributes */
    GetConsoleScreenBufferInfo(hConsole, &consoleInfo);
    saved_attributes = consoleInfo.wAttributes;

    SetConsoleTextAttribute(hConsole, FOREGROUND_BLUE);
    printf("This is some nice COLORFUL text, isn't it?");

    /* Restore original attributes */
    SetConsoleTextAttribute(hConsole, saved_attributes);
    printf("Back to normal");

    return 0;
}

For more info on the available attributes, look here.

Hope this helps! :)

like image 90
Miguel Avatar answered Oct 11 '22 11:10

Miguel