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

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 color
	GetConsoleScreenBufferInfo(h, &csbiInfo);
	wOldColorAttrs = csbiInfo.wAttributes;

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

	// Restore the original color
	SetConsoleTextAttribute(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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值