如何更改 Windows 控制台应用程序中的文本或背景颜色

2021-12-22 00:00:00 text background-color c++

哪个 C++ 函数会更改文本或背景颜色(MS Visual Studio)?比如cout<<"This text";如何让"This text"变成红色.

Which C++ function changes text or background color (MS Visual studio)? For example cout<<"This text"; how to make "This text" red color.

推荐答案

颜色不是 C++ 的东西,而是 终端 的属性.如果您的终端使用 ANSI(例如,任何 Linux 终端,或 DOS 或 Windows NT,如果您将 DEVICE=C:DOSansi.sys 添加到您的 config.sys,或以后的Windows如果你用cmd.exe/kansicon调用shell,那么你可以试试下面的噱头:

Colour isn't a C++ thing, but a property of your terminal. If your terminal speaks ANSI (e.g. any Linux terminal, or DOS or Windows NT if you add DEVICE=C:DOSansi.sys to your config.sys, or later Windows if you call the shell with cmd.exe /kansicon), then you can try the following gimmick:

#define ANSI_COLOR_RED     "x1b[31m"
#define ANSI_COLOR_GREEN   "x1b[32m"
#define ANSI_COLOR_YELLOW  "x1b[33m"
#define ANSI_COLOR_BLUE    "x1b[34m"
#define ANSI_COLOR_MAGENTA "x1b[35m"
#define ANSI_COLOR_CYAN    "x1b[36m"

#define ANSI_COLOR_BRIGHT  "x1b[1m"
#define ANSI_COLOR_RESET   "x1b[0m"


std::cout << ANSI_COLOR_RED "Hello World
" ANSI_COLOR_RESET;

维基百科有一个ANSI 转义序列列表.

相关文章