Windows下用C语言设置控制台颜色

C语言小程序在Windows下设置控制台颜色

其实很简单,主要通过SetConsoleTextAttribute函数的参数。关于这个函数的原始声明,可以查找MSDN的API说明,也可见下文。
改变第二个参数后,再加上简单的循环,可以得到很有趣的效果,就像下图的色表:
cmdcolor
其实现代码如下:

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

int main(void)
{
HANDLE consolehwnd;//创建句柄,详细句柄知识,请百度一下或查MSDN
consolehwnd = GetStdHandle(STD_OUTPUT_HANDLE);//实例化句柄
SetConsoleTextAttribute(consolehwnd, 15);
printf(" Console color list...\n");
for (int i = 0; i < 256; i++)
{
SetConsoleTextAttribute(consolehwnd, i);
printf("%5d", i);
}
SetConsoleTextAttribute(consolehwnd, 15);
printf("hello!\n");
printf("It is really beautiful!\n");
system("pause");
return 0;
}

SetConsoleTextAttribute()函数原型

SetConsoleTextAttribute function
Sets the attributes of characters written to the console screen buffer by the WriteFile or WriteConsole function, or echoed by the ReadFile or ReadConsole function. This function affects text written after the function call.

Syntax

BOOL WINAPI SetConsoleTextAttribute(
_In_ HANDLE hConsoleOutput,
_In_ WORD wAttributes
);

Parameters

hConsoleOutput [in]

A handle to the console screen buffer. The handle must have the GENERIC_READ access right. For more information, see Console Buffer Security and Access Rights.

wAttributes [in]

The character attributes.

Return value

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.

Examples

For an example, see Using the High-Level Input and Output Functions.

Requirements

Minimum supported client
Windows 2000 Professional [desktop apps only]
Minimum supported server
Windows 2000 Server [desktop apps only]

Header

Wincon.h (include Windows.h)

Library

Kernel32.lib

DLL

Kernel32.dll