C程序之修改Windows的控制台颜色(转载)

Windows的CMD可以和Linux下的终端一样可以有五颜六色,目前我在网上找到2种方法可以修改Windows的CMD,当然都是在代码中修改的。在“CMD”->“属性”->“颜色”,这种方法就另当别论了。

        (1)方法一:调用color命令行程序

Windows的CMD中有个color命令,它可以修改控制台的前景色和背景色,用法如下:

利用C的system函数,就可以调用color这个命令,代码如下

#include <stdio.h>  
#include <stdlib.h>  
  
void main(void)  
{  
    system("color fc");  
    printf("This is a test
");  
}  

这种方法只能对整个控制台设置颜色,不能对一段字符串设置特殊的颜色。

(2)方法二:调用Windows的API

下面的代码,展示如何修改前景色和背景色,可以对一段字符串设置不同的颜色。

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

void main(void)
{
    HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);
    WORD wOldColorAttrs;
    CONSOLE_SCREEN_BUFFER_INFO csbiInfo;

    // Save the current color
    GetConsoleScreenBufferInfo(h, &csbiInfo);
    wOldColorAttrs = csbiInfo.wAttributes;

    // Set the new color
    SetConsoleTextAttribute(h, FOREGROUND_RED | FOREGROUND_INTENSITY | BACKGROUND_GREEN);
    printf("This is a test
");

    // Restore the original color
    SetConsoleTextAttribute(h, wOldColorAttrs);
    printf("This is a test
");
}

原文:C程序中修改Windows的控制台颜色

原文地址:https://www.cnblogs.com/iloverain/p/5642549.html