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

来源:互联网 发布:深度linux安装apk 编辑:程序博客网 时间:2024/05/10 05:21

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\n");}

效果如下


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

 

        (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 colorGetConsoleScreenBufferInfo(h, &csbiInfo);wOldColorAttrs = csbiInfo.wAttributes;// Set the new colorSetConsoleTextAttribute(h, FOREGROUND_RED | FOREGROUND_INTENSITY | BACKGROUND_GREEN);printf("This is a test\n");// Restore the original colorSetConsoleTextAttribute(h, wOldColorAttrs);printf("This is a test\n");}

效果如下



参考资料:

1、http://faq.cprogramming.com/cgi-bin/smartfaq.cgi?answer=1048382857&id=1043284392

2、http://www.wibit.net/forums/courses/programming_c/console_color_windows

3、http://hi.baidu.com/807008101/item/010813261869693795f62bf0