代码改变世界

改变控制台的输出颜色

2013-06-05 22:44  钱吉  阅读(345)  评论(0编辑  收藏  举报

  这里面只需要用到Windows API的一个函数:SetConsoleTextAttribute

msdn上的说明如下:
BOOL SetConsoleTextAttribute(
  HANDLE hConsoleOutput,  // handle to screen buffer
  WORD wAttributes        // text and background colors
);

Parameters

hConsoleOutput
[in] Handle to a console screen buffer. The handle must have GENERIC_READ access.
wAttributes
[in] Specifies the foreground and background color attributes. Any combination of the following values can be specified: FOREGROUND_BLUE, FOREGROUND_GREEN, FOREGROUND_RED, FOREGROUND_INTENSITY, BACKGROUND_BLUE, BACKGROUND_GREEN, BACKGROUND_RED, and BACKGROUND_INTENSITY. For example, the following combination of values produces white text on a black background:
FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE 

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

To determine the current color attributes of a screen buffer, call the GetConsoleScreenBufferInfo function.

 

我们的使用如下:

#include <windows.h>
#include <stdio.h>
#include <stdlib.h>

BOOL SetConsolColor(DWORD stdHandle, DWORD wAttributes=0x07UL)
{
    HANDLE handle = GetStdHandle(stdHandle);
    if(NULL == handle) {
        return;
    }
    return SetConsoleTextAttribute(handle, wAttributes);
}
int _tmain(int argc, _TCHAR* argv[])
{
    SetConsolColor(STD_OUTPUT_HANDLE, FOREGROUND_RED|BACKGROUND_GREEN);
    printf("输出:绿底红字\n");
    //SetConsolColor(STD_OUTPUT_HANDLE, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
    SetConsolColor(STD_OUTPUT_HANDLE);
    printf("默认:黑底白字\n");
    return 0;
}

输出效果: