Colorized output in Visual C++

  • 函数定义
#pragma once

enum COLORS
{
    BLACK = 0,
    DARK_BLUE = 1,
    DARK_GREEN = 2,
    DARK_CYAN = 3,
    DARK_RED = 4,
    DARK_MAGENTA = 5,
    DARK_YELLOW = 6,
    GRAY = 7,
    DARK_GRAY = 8,
    BLUE = 9,
    GREEN = 10,
    CYAN = 11,
    RED = 12,
    MAGENTA = 13,
    YELLOW = 14,
    WHITE = 15,
};

int _setforecolor(int color);
int _setbackcolor(int color);
void _fillconsoleattr(int attr);
#include <Windows.h>
#include <conio.h>
#include "console.h"

int _setforecolor(int color)
{
    HANDLE hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
    CONSOLE_SCREEN_BUFFER_INFO csbi;
    GetConsoleScreenBufferInfo(hStdout, &csbi);
    SetConsoleTextAttribute(hStdout, csbi.wAttributes & 0xF0 | color);
    return (csbi.wAttributes & 0x0F);
}

int _setbackcolor(int color)
{
    HANDLE hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
    CONSOLE_SCREEN_BUFFER_INFO csbi;
    GetConsoleScreenBufferInfo(hStdout, &csbi);
    SetConsoleTextAttribute(hStdout, csbi.wAttributes & 0x0F | (color << 4));
    return (csbi.wAttributes & 0xF0) >> 4;
}

void _fillconsoleattr(int attr)
{
    DWORD nWritten = 0;
    HANDLE hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
    CONSOLE_SCREEN_BUFFER_INFO csbi;
    GetConsoleScreenBufferInfo(hStdout, &csbi);
    FillConsoleOutputAttribute(hStdout, attr, csbi.dwSize.X * csbi.dwSize.Y, { 0, 0 }, &nWritten);
}
  • 测试程序
#include <iostream>
#include "console.h"

int main()
{
    std::cout << "Hello World!\n"; 
    _setforecolor(YELLOW);
    std::cout << "Yellow\n";
    _setbackcolor(DARK_BLUE);
    std::cout << "DarkBlue Background\n";
}
  • 输出结果
Hello World!
Yellow
DarkBlue Background