在 C 和 C++ 中更改控制台输出的背景颜色
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20725769/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Change background color of console output in C and C++
提问by user2948288
I change the background and text color in my console by using the "system" command.
我使用“system”命令更改了控制台中的背景和文本颜色。
#include <iostream>
using namespace std;
int main()
{
system ("color 1a");
cout <<"Hello World";
cin.ignore();
return 0;
}
Is there a way to change color in only one line? C or C++ are fine. Thanks.
有没有办法只在一行中改变颜色?C 或 C++ 都很好。谢谢。
回答by mcleod_ideafix
I assume you are using Windows, as your system()
function is executing color
which is a console utility for Windows.
我假设您使用的是 Windows,因为您的system()
函数正在执行color
,这是 Windows 的控制台实用程序。
If you are going to write your program for Windows and you want to change color of text and/or background, use this:
如果您要为 Windows 编写程序并且想要更改文本和/或背景的颜色,请使用以下命令:
SetConsoleTextAttribute (GetStdHandle(STD_OUTPUT_HANDLE), attr);
Where attr
is a combination of values with |
(bitwise OR operator), to choose whther you want to change foreground or background color. Changes apply with the next function that writes to the console (printf()
for example).
attr
值与|
(按位或运算符)的组合在哪里,以选择要更改前景色还是背景色。更改适用于写入控制台的下一个函数(printf()
例如)。
Details about how to encode the attr
argument, here:
http://msdn.microsoft.com/en-us/library/windows/desktop/ms682088%28v=vs.85%29.aspx#_win32_character_attributes
有关如何对attr
参数进行编码的详细信息,请访问:http:
//msdn.microsoft.com/en-us/library/windows/desktop/ms682088%28v=vs.85%29.aspx#_win32_character_attributes
For example, this programs prints "Hello world" using yellow text (red+green+intensity) over blue background, in a computer with Windows 2000 or later:
例如,此程序在装有 Windows 2000 或更高版本的计算机中使用蓝色背景上的黄色文本(红色+绿色+强度)打印“Hello world”:
#include <stdio.h>
#include <windows.h>
int main()
{
SetConsoleTextAttribute (GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_RED |
FOREGROUND_GREEN |
FOREGROUND_INTENSITY |
BACKGROUND_BLUE
);
printf ("Hello world\n");
return 0;
}
This other shows a color chart showing all combinations for foreground and background colors:
另一个显示了一个颜色图表,显示了前景色和背景色的所有组合:
#include <stdio.h>
#include <windows.h>
int main()
{
unsigned char b,f;
for (b=0;b<16;b++)
{
for (f=0;f<16;f++)
{
SetConsoleTextAttribute (GetStdHandle(STD_OUTPUT_HANDLE), b<<4 | f);
printf ("%.2X", b<<4 | f);
}
printf ("\n");
}
SetConsoleTextAttribute (GetStdHandle(STD_OUTPUT_HANDLE), 0x07);
printf ("\n");
return 0;
}