/* 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
改变控制台的文字背景颜色
最新推荐文章于 2021-04-08 17:17:59 发布