如何将控制台输出的文本颜色更改为红色,但如果从Powershell或CMD运行,背景将保持相同的颜色
How can you change the text color of console output to red, but background remains the same color if ran from Powershell or CMD
在Windows中,我希望我的程序将文本输出到控制台,只为程序的一行为红色。但是,我希望无论程序是从Powershell还是cmd运行,背景都保持不变。
我试过使用句柄
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hConsole, color);
cout << text;
这将更改背景。如果我匹配cmd的默认黑色背景(如果颜色为0-15(,它会在Powershell的默认深蓝色背景上显示Powershell中黑色背景的文本。
我希望有人从CMD或Powershell运行该程序,背景颜色不会改变,但文本会改变。
多亏了immibis,我得到了答案。我需要获取当前的控制台颜色,然后我可以从那里开始。
CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
int defaultColor = 7;
int redColor = 12;
if (GetConsoleScreenBufferInfo(hConsole, &csbiInfo)) //This gets the color
{
defaultColor = csbiInfo.wAttributes; //This is where the current color is stored
redColor = (defaultColor / 16) * 16 + 12; //Keeps the background color, sets the text to red
}
SetConsoleTextAttribute(hConsole, redColor);
cout << "This is red!n";
SetConsoleTextAttribute(hConsole, defaultColor);
cout << "Back to Normal!";
相关文章:
- 运行同一解决方案的另一个项目的项目
- CMake-按正确顺序将项目与C运行时对象文件链接
- 如何运行位于boost/libs/python/example/tutorial目录中的hello.cpp和Jamfil
- 代码在main()中运行,但在函数中出现错误
- 我在c++代码中生成了一个运行时#3异常
- 如何在linux终端中同时编译和运行c++代码
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 如何在运行中期切换GTK CSS style_context
- 将"打开的CV图像"中的"颜色"转换为整数格式
- 如何在MS Visual Studio 2019中运行QT UI
- 如何通过cpp程序运行shell脚本
- IPC使用多个管道和分支进程来运行Python程序
- 删除指向指针的指针是运行时错误吗
- 如何用参数值调用函数(仅在运行时已知)
- 为什么即使使用-cudart-static进行编译,库用户仍然需要链接到cuda运行时
- 是否可以在编译时初始化数组,以便在运行时不会花费时间?
- 如何将控制台输出的文本颜色更改为红色,但如果从Powershell或CMD运行,背景将保持相同的颜色
- 如何在 Ogre3D 中检索模型顶点的运行时颜色
- BASH下运行程序的颜色输出
- 我如何在'opencv'函数,当我构建隐藏窗口(在后台运行)时获得像素的颜色