输出彩色的控制台文字

 

#include <iostream>
#include <Windows.h>
#include <stdio.h>
#include <stdarg.h>

using namespace std;

void cprintf(const char* str, WORD color, ...);
void testPrintf();

int main() {
    cprintf("H", 10);
    cprintf("e", 9);
    cprintf("l", 12);
    cprintf("l", 11);
    cprintf("o", 13);
    cprintf(" ", 10);
    cprintf("W", 15);
    cprintf("o", 2);
    cprintf("r", 5);
    cprintf("l", 8);
    cprintf("d", 14);
    cprintf("!", 4);

    testPrintf();

    return 0;
}

void cprintf(const char* str, WORD color, ...) {
    WORD colorOld;
    HANDLE handle = ::GetStdHandle(STD_OUTPUT_HANDLE);
    CONSOLE_SCREEN_BUFFER_INFO csbi;
    GetConsoleScreenBufferInfo(handle, &csbi);
    colorOld = csbi.wAttributes;
    SetConsoleTextAttribute(handle, color);
    cout << str;
    SetConsoleTextAttribute(handle, colorOld);
}

void testPrintf() {

    WORD colorOld;
    HANDLE handle = ::GetStdHandle(STD_OUTPUT_HANDLE);
    CONSOLE_SCREEN_BUFFER_INFO csbi;
    GetConsoleScreenBufferInfo(handle, &csbi);
    colorOld = csbi.wAttributes;

    cout << endl;
    //https://docs.microsoft.com/zh-cn/windows/console/console-screen-buffers#character-attributes
    SetConsoleTextAttribute(handle, FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_INTENSITY | BACKGROUND_BLUE);//以下组合实现:蓝色背景上的亮青色文本。
    cout << "123" << endl;
    SetConsoleTextAttribute(handle, BACKGROUND_BLUE | BACKGROUND_GREEN | BACKGROUND_RED);//以下组合实现:白色背景上的黑色文本。
    cout << "456" << endl;
    SetConsoleTextAttribute(handle, colorOld);//恢复原来样式
}

 

 

 

 

 

转: https://www.cnblogs.com/finlay/archive/2013/06/09/3234729.html

 

相关文章:

  • 2021-10-19
  • 2021-04-05
  • 2021-06-16
  • 2021-12-05
  • 2021-06-15
  • 2021-12-29
  • 2022-02-18
猜你喜欢
  • 2021-09-22
  • 2022-12-23
  • 2022-12-23
  • 2021-04-04
  • 2022-01-19
  • 2022-12-23
  • 2021-12-17
相关资源
相似解决方案