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

来源:互联网 发布:qt windows sdk下载 编辑:程序博客网 时间:2024/05/21 13:53

原址链接:点击打开链接

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

 

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

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

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


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

[cpp] view plaincopy
  1. #include <stdio.h>  
  2. #include <stdlib.h>  
  3.   
  4. void main(void)  
  5. {  
  6.     system("color fc");  
  7.     printf("This is a test\n");  
  8. }  

效果如下


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

 

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

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

[cpp] view plaincopy
  1. #include <stdio.h>  
  2. #include <Windows.h>  
  3.   
  4. void main(void)  
  5. {  
  6.     HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);  
  7.     WORD wOldColorAttrs;  
  8.     CONSOLE_SCREEN_BUFFER_INFO csbiInfo;  
  9.   
  10.     // Save the current color  
  11.     GetConsoleScreenBufferInfo(h, &csbiInfo);  
  12.     wOldColorAttrs = csbiInfo.wAttributes;  
  13.   
  14.     // Set the new color  
  15.     SetConsoleTextAttribute(h, FOREGROUND_RED | FOREGROUND_INTENSITY | BACKGROUND_GREEN);  
  16.     printf("This is a test\n");  
  17.   
  18.     // Restore the original color  
  19.     SetConsoleTextAttribute(h, wOldColorAttrs);  
  20.     printf("This is a test\n");  
  21. }  

效果如下



参考资料:

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

0 0