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

半腔热情 提交于 2019-11-29 11:08:28

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!