在 Windows 中设置 stdout/stderr 文本颜色
我尝试使用 system("color 24");
但这并没有改变提示中的颜色。因此,经过更多谷歌搜索后,我看到了 SetConsoleTextAttribute
并编写了以下代码。
这会导致 stdout
和 stderr
都变成红色,而不是 stdout
为绿色,stderr
为红色。
我该如何解决这个问题?我的提示现在也是红色的,但我不在乎,因为我知道如何修复它。
应该在 Windows 7 中工作。目前我正在从提示符(使用 VS 2010 cl)构建它并在常规 cmd
提示符中运行它
#include <windows.h>
#include <stdio.h>
int main(int argc, char **argv)
{
int i;
unsigned long totalTime=0;
HANDLE hConsoleOut; //handle to the console
hConsoleOut = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hConsoleOut, FOREGROUND_GREEN);
HANDLE hConsoleErr;
hConsoleErr = GetStdHandle(STD_ERROR_HANDLE);
SetConsoleTextAttribute(hConsoleErr, FOREGROUND_RED);
fprintf(stdout, "%s\n", "out");
fprintf(stderr, "%s\n", "err");
return 0;
}
I tried using system("color 24");
but that didn't change the color in the prompt. So after more Googling I saw SetConsoleTextAttribute
and wrote the below code.
This results in both stdout
and stderr
both getting colored red instead of stdout
being green and stderr
being red.
How do I solve this? My prompt is also now red but I don't care about that since I know how to fix it.
Should work in Windows 7. At the moment I'm building this from the prompt (using VS 2010 cl) and running it in a regular cmd
prompt
#include <windows.h>
#include <stdio.h>
int main(int argc, char **argv)
{
int i;
unsigned long totalTime=0;
HANDLE hConsoleOut; //handle to the console
hConsoleOut = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hConsoleOut, FOREGROUND_GREEN);
HANDLE hConsoleErr;
hConsoleErr = GetStdHandle(STD_ERROR_HANDLE);
SetConsoleTextAttribute(hConsoleErr, FOREGROUND_RED);
fprintf(stdout, "%s\n", "out");
fprintf(stderr, "%s\n", "err");
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
根据 MSDN
GetStdHandle()
文档,该函数将返回同一活动控制台屏幕缓冲区的句柄。因此,使用这些句柄设置属性将始终更改相同的缓冲区。因此,您必须在访问输出设备之前指定颜色:According to the MSDN
GetStdHandle()
documentation, the function will return handles to the same active console screen buffer. So setting attributes using these handles will always change the same buffer. Because of this you have to specify the color right before you right to the output device:错误句柄和正常控制台输出是相同的。或者更像是,它们指向同一个控制台窗口。当您更改控制台颜色时,它会应用于此后编写的所有文本,因此您需要在输出之前直接更改颜色。如果您不想对输出的每个文本都执行此操作,请将调用打包到单独的函数中:
The handle for error and normal console output are the same. Or more like, they point to the same console window. When you change the console color, it applies to all text written after that, so you'd need to change the color directly before the output. If you don't want to do that for every text you output, pack the calls into a seperate function:
尝试在每次输出之前设置颜色。您可以在函数中执行此操作以避免代码重复。
Try to set the color before each output. You can do that in a function to avoid code duplication.