在Windows中设置stdout / stderr文本颜色 [英] Setting stdout/stderr text color in Windows

查看:368
本文介绍了在Windows中设置stdout / stderr文本颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用 system(color 24); 但是没有改变提示中的颜色。所以更多的Google之后,我看到 SetConsoleTextAttribute 并写下面的代码。

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.

这会导致 stdout stderr 都变成红色而不是 stdout $ c> stderr 为红色。

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.

应该在Windows 7中工作。这是从提示符(使用VS 2010 cl)并在常规 cmd 提示符

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;
}


推荐答案

根据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:

/* ... */

HANDLE hConsoleOut; //handle to the console
HANDLE hConsoleErr;
hConsoleErr = GetStdHandle(STD_ERROR_HANDLE);
hConsoleOut = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hConsoleOut, FOREGROUND_GREEN);
fprintf(stdout, "%s\n", "out");

SetConsoleTextAttribute(hConsoleErr, FOREGROUND_RED);
fprintf(stderr, "%s\n", "err");
return 0;

这篇关于在Windows中设置stdout / stderr文本颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆