Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Colorize stdout output to Windows cmd.exe from console C++ app

I would like to write something similar to

cout << "this text is not colorized\n";
setForeground(Color::Red);
cout << "this text shows as red\n";
setForeground(Color::Blue);
cout << "this text shows as blue\n";

for a C++ console program running under Windows 7. I have read that global foreground & background can be changed from cmd.exe's settings, or by calling system() - but is there any way to change things at character-level that can be coded into a program? At first I thought "ANSI sequences", but they seem to be long lost in the Windows arena.

like image 669
tucuxi Avatar asked Oct 15 '11 14:10

tucuxi


2 Answers

You can use SetConsoleTextAttribute function:

BOOL WINAPI SetConsoleTextAttribute(
  __in  HANDLE hConsoleOutput,
  __in  WORD wAttributes
);

Here's a brief example which you can take a look.

#include "stdafx.h"
#include <iostream>
#include <windows.h>
#include <winnt.h>
#include <stdio.h>
using namespace std;

int main(int argc, char* argv[])
{
   HANDLE consolehwnd = GetStdHandle(STD_OUTPUT_HANDLE);
   cout << "this text is not colorized\n";
   SetConsoleTextAttribute(consolehwnd, FOREGROUND_RED);
   cout << "this text shows as red\n";
   SetConsoleTextAttribute(consolehwnd, FOREGROUND_BLUE);
   cout << "this text shows as blue\n";
}

This function affects text written after the function call. So finally you probably want to restore to the original color/attributes. You can use GetConsoleScreenBufferInfo to record the initial color at the very beginning and perform a reset w/ SetConsoleTextAttribute at the end.

like image 105
Eric Z Avatar answered Sep 30 '22 08:09

Eric Z


Take a look at http://gnuwin32.sourceforge.net/packages/ncurses.htm

like image 20
André Puel Avatar answered Sep 30 '22 08:09

André Puel