zoukankan      html  css  js  c++  java
  • C++ 输出彩色的控制台

    输出彩色的控制台文字

    #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

  • 相关阅读:
    P1962 斐波那契数列(矩阵加速DP)
    P1939 【模板】矩阵加速(数列)
    剑指04.重建二叉树
    剑指03.从尾到头打印链表
    剑指02.替换空格
    剑指01.二维数组中的查找
    Python绘图学习笔记(待完善)
    时间观念 目标观念
    购房交税
    可以不做会计,但是不能不懂会计
  • 原文地址:https://www.cnblogs.com/fps2tao/p/15078195.html
Copyright © 2011-2022 走看看