改变控制台的文字背景颜色

本文介绍如何使用Windows API函数GetConsoleScreenBufferInfo和SetConsoleTextAttribute来获取和设置控制台的文字和背景颜色,并提供了实现这些功能的具体代码示例。

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

/*      ConsoleColor.H


 relevant windows API

1、 GetConsoleScreenBufferInfo(HANDLE handle , PCONSOLE_SCREEN_BUFFER_INFO pCsbi);
获得consoleScreenBuffer的信息存在pcsbi指向的空间中。

2、 SetConsoleTextAttribute(HANDLE handle , WORD attribute);
 设置控制consoleScreen颜色信息的变量wattribute为attribute值。



附:
1、CONSOLE_SCREEN_BUFFER_INFO中的wattribute属性是用来存储控制台的字体和背景颜色的,wattribute的最后4位存储文字颜色,倒退4位存储背景色
2、handle可用 GetStdHandle(STD_OUTPUT_HANDLE)来求得。
*/

#ifndef _CONSOLE_COLOR
#define _CONSOLE_COLOR


#ifndef _INC_WINDOWS
#include <WINDOWS.H>
#endif



enum concol
{
		black=0,
		dark_blue=1,
		dark_green=2,
		dark_aqua,dark_cyan=3,
		dark_red=4,
		dark_purple=5,dark_pink=5,dark_magenta=5,
		dark_yellow=6,
		dark_white=7,
		gray=8,
		blue=9,
		green=10,
		aqua=11,cyan=11,
		red=12,
		purple=13,pink=13,magenta=13,
		yellow=14,
		white=15,
		DEFAULT_TEXT=7,
		DEFAULT_BACK=0
};


#define console_output_handle (GetStdHandle(STD_OUTPUT_HANDLE))

concol getConsoleScreenBackColor();
concol getConsoleScreenTextColor();
void setConsoleScreenBackColor(concol back);
void setConsoleScreenTextColor(concol text);
void setConsoleScreenColor(concol text, concol back);






concol getConsoleScreenBackColor()
{
	CONSOLE_SCREEN_BUFFER_INFO csbi;
	GetConsoleScreenBufferInfo(console_output_handle , &csbi);
	return (concol)(csbi.wAttributes/16%16);
}



concol getConsoleScreenTextColor()
{
	CONSOLE_SCREEN_BUFFER_INFO csbi;
	GetConsoleScreenBufferInfo(console_output_handle , &csbi);
	return (concol)(csbi.wAttributes%16);
}



void setConsoleScreenBackColor(concol back)
{
	unsigned short attribute=(back<<4) | getConsoleScreenTextColor();
	SetConsoleTextAttribute(console_output_handle,attribute);
}



void setConsoleScreenTextColor(concol text)
{
	unsigned short attribute=(getConsoleScreenBackColor()<<4) | text;
	SetConsoleTextAttribute(console_output_handle,attribute);
}



void setConsoleScreenColor(concol text , concol back)
{
	unsigned short attribute=back<<4 |text;
	SetConsoleTextAttribute(console_output_handle,attribute);
}




ostream& operator<<(ostream& os, concol text)
{
	unsigned attribute=(getConsoleScreenBackColor()<<4) | text;
	SetConsoleTextAttribute(console_output_handle,attribute);
	return os;
}



istream& operator>>(istream& is, concol text)
{
	unsigned attribute=(getConsoleScreenBackColor()<<4) | text;
	SetConsoleTextAttribute(console_output_handle,attribute);
	return is;
}


#endif


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值