输出彩色文字到窗口的代码,参考自googletest

这篇博客展示了如何在Windows环境下利用<Windows.h>库来输出彩色文字。通过定义不同的颜色枚举并调用GetColorAttribute函数,可以在控制台中改变文字颜色。示例代码中,ColoredPrintf函数用于格式化并输出指定颜色的文字。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include "stdafx.h"
#include <stdio.h>
/*输出彩色文字需要使用下列头文件*/
#include <Windows.h>
#include <io.h>

#define  GTEST_OS_WINDOWS 1

enum GTestColor {
    COLOR_DEFAULT,
    COLOR_RED,
    COLOR_GREEN,
    COLOR_YELLOW
};

WORD GetColorAttribute(GTestColor color);

#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE

// Returns the character attribute for the given color.
WORD GetColorAttribute(GTestColor color) {
    switch (color) {
    case COLOR_RED:    return FOREGROUND_RED;
    case COLOR_GREEN:  return FOREGROUND_GREEN;
    case COLOR_YELLOW: return FOREGROUND_RED | FOREGROUND_GREEN;
    default:           return 0;
    }
}

#else

// Returns the ANSI color code for the given color.  COLOR_DEFAULT is
// an invalid input.
const char* GetAnsiColorCode(GTestColor color) {
    switch (color) {
    case COLOR_RED:     return "1";
    case COLOR_GREEN:   return "2";
    case COLOR_YELLOW:  return "3";
    default:            return NULL;
    };
}

#endif 



void ColoredPrintf(GTestColor color, const char* fmt, ...) {
    va_list args;
    va_start(args, fmt);
    const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
    CONSOLE_SCREEN_BUFFER_INFO buffer_info;
    GetConsoleScreenBufferInfo(stdout_handle, &buffer_info);

    const WORD old_color_attrs = buffer_info.wAttributes;
    fflush(stdout);

    SetConsoleTextAttribute(stdout_handle,
        GetColorAttribute(color) | FOREGROUND_INTENSITY);
    vprintf(fmt, args);
    fflush(stdout);
    // Restores the text color.
    SetConsoleTextAttribute(stdout_handle, old_color_attrs);
    va_end(args);
}




int _tmain(int argc, _TCHAR* argv[])
{   

    ColoredPrintf(COLOR_YELLOW,"\nMy test output color fonts.");
    ColoredPrintf(COLOR_RED," test again.");
    getchar();
    return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值