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

前端 未结 2 1307
执笔经年
执笔经年 2020-12-19 12:09

I would like to write something similar to

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


        
相关标签:
2条回答
  • 2020-12-19 12:24

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

    0 讨论(0)
  • 2020-12-19 12:41

    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.

    0 讨论(0)
提交回复
热议问题