改变控制台输出颜色

今天看见比较有意思的代码,放在这里一方面以是备份
用法
cout << blue << "hello" << endl;
代码:
#pragma once
#include <windows.h>
#include <iostream>
using namespace std;



inline std::ostream& blue(std::ostream &s)
{
    HANDLE hStdout = GetStdHandle(STD_OUTPUT_HANDLE); 
    SetConsoleTextAttribute(hStdout, FOREGROUND_BLUE
|FOREGROUND_GREEN|FOREGROUND_INTENSITY);
    return s;
}


inline std::ostream& red(std::ostream &s)
{
    HANDLE hStdout = GetStdHandle(STD_OUTPUT_HANDLE); 
    SetConsoleTextAttribute(hStdout, 
FOREGROUND_RED|FOREGROUND_INTENSITY);
    return s;
}


inline std::ostream& green(std::ostream &s)
{
    HANDLE hStdout = GetStdHandle(STD_OUTPUT_HANDLE); 
    SetConsoleTextAttribute(hStdout, 
FOREGROUND_GREEN|FOREGROUND_INTENSITY);
    return s;
}


inline std::ostream& yellow(std::ostream &s)
{
    HANDLE hStdout = GetStdHandle(STD_OUTPUT_HANDLE); 
    SetConsoleTextAttribute(hStdout, 
FOREGROUND_GREEN|FOREGROUND_RED|FOREGROUND_INTENSITY);
    return s;
}


inline std::ostream& white(std::ostream &s)
{
    HANDLE hStdout = GetStdHandle(STD_OUTPUT_HANDLE); 
    SetConsoleTextAttribute(hStdout, 
FOREGROUND_RED|FOREGROUND_GREEN|FOREGROUND_BLUE);
    return s;
}


struct color {
    color(WORD attribute):m_color(attribute){};
    WORD m_color;
};


template <class _Elem, class _Traits>
std::basic_ostream<_Elem,_Traits>& 
operator<<(std::basic_ostream<_Elem,_Traits>& i, color& c)
{
    HANDLE hStdout=GetStdHandle(STD_OUTPUT_HANDLE); 
    SetConsoleTextAttribute(hStdout,c.m_color);
    return i;
}


你可能感兴趣的:(c,struct,basic,Class,output)