C

c – Output coloured text to a Windows terminal

GetStdHandle function retrieves a handle to the specified standard device (standard input, standard output, or standard error).

GetConsoleScreenBufferInfo function retrieves information about the specified console screen buffer.

SetConsoleTextAttribute function sets the attributes of characters written to the console screen buffer by the WriteFile or WriteConsole function, or echoed by the ReadFile or ReadConsole function. This function affects text written after the function call.

Header

#ifndef COLORAMA_H_
#define COLORAMA_H_
 
#include 
#include 
 
#define FOREGROUND_BLACK		0x0
#define FOREGROUND_AQUA			0x3
#define FOREGROUND_PURPLE		0x5
#define FOREGROUND_YELLOW		0x6
#define FOREGROUND_WHITE		0x7
#define FOREGROUND_GRAY			0x8
#define FOREGROUND_LIGHT_BBLUE	0x9
#define FOREGROUND_LIGHT_GREEN	0xA
#define FOREGROUND_LIGHT_AQUA	0xB
#define FOREGROUND_LIGHT_RED	0xC
#define FOREGROUND_LIGHT_PURPLE	0xD
#define FOREGROUND_LIGHT_YELLOW	0xE
#define FOREGROUND_BRIGHT_WHITE	0xF
 
int printColored(WORD wColorAttrs, const char *format, ...);
HANDLE StartColoring(WORD wNewColorAttrs, WORD *wOldColorAttrs);
int EndColoring(HANDLE hStdout, WORD wOldColorAttrs);
 
#endif

Source

#include "colorama.h"
 
int printColored(WORD wColorAttrs, const char *format, ...){
 
	va_list arglist;
	int written = 0;
 
	va_start(arglist, format);
 
	HANDLE hStdout = INVALID_HANDLE_VALUE;
	WORD wOldColorAttrs = 0;
 
	hStdout = StartColoring(wColorAttrs, &wOldColorAttrs);
 
	written = vprintf(format, arglist);
 
	va_end(arglist);
	EndColoring(hStdout, wOldColorAttrs);
 
	return written;
}
 
HANDLE StartColoring(WORD wNewColorAttrs, WORD *wOldColorAttrs){
 
	HANDLE hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
	CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
 
	if (hStdout == INVALID_HANDLE_VALUE)
	{
		return INVALID_HANDLE_VALUE;
	}
 
	if (! GetConsoleScreenBufferInfo(hStdout, &csbiInfo))
	{
		return INVALID_HANDLE_VALUE;
	}
 
	*wOldColorAttrs = csbiInfo.wAttributes;
 
	if (! SetConsoleTextAttribute(hStdout, wNewColorAttrs))
	{
		return INVALID_HANDLE_VALUE;
	}
 
	return hStdout;
}
 
int EndColoring(HANDLE hStdout, WORD wOldColorAttrs){
 
	if(hStdout == INVALID_HANDLE_VALUE) return FALSE;
 
	if(! SetConsoleTextAttribute(hStdout, wOldColorAttrs))
	{
		return FALSE;
	}
 
	return TRUE;
}

Example

#include "colorama.h"
 
int main()
{
	printColored(FOREGROUND_RED | FOREGROUND_INTENSITY,
			"\n"
			"\n"
			"test1\n"
			"test2\n"
			"test3\n"
			"\n");
 
	printColored(FOREGROUND_BRIGHT_WHITE | FOREGROUND_INTENSITY, "test");
 
	printColored(FOREGROUND_YELLOW | FOREGROUND_INTENSITY, "test %s\n", "test");
 
	return 0;
}

Download
Download from Gist.