C language is not always "white on black background", it can also be colored, you can call Windows.h
the SetConsoleTextAttribute
function under the header file to change the text and background color.
The call form is:
SetConsoleTextAttribute( HANDLE hConsoleOutput, WORD wAttributes );
hConsoleOutput
Indicates the handle of the console buffer, which can be obtained through GetStdHandle(STD_OUTPUT_HANDLE)
; wAttributes
Indicates the text color and background color.
I will not pursue the meaning of HANDLE here, and I will explain it in detail in Windows development later.
WORD
In windows.h
the definitions, equivalent to unsigned short
, the use of lower 4 bits represent text (foreground) color, upper four bits represent the text background color, so that its value is xx
. x is a hexadecimal number, that is, 0~F
both can be used and can be combined at will.
The colors represented by 0~F are as follows:
0 = black 8 = gray 1 = light blue 9 = blue
2 = light green A = green 3 = lake blue B = light light green
C = red 4 = light red 5 = purple D
= light purple 6 = yellow E = light Yellow 7 = white F = bright white
For example, set the background to light green and the text to red:
#include <stdio.h>
#include <windows.h>
int main(){
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hConsole, 0x2C );
puts("C语言中文网");
return 0;
}
Running result:
If you only want to set the text color and keep the background black, you can also give only a hexadecimal number, for example:
SetConsoleTextAttribute(hConsole, 0xC ); //Set the text color to red SetConsoleTextAttribute(hConsole, 0xF ); //Set the text color to white
Let's look at another example:
#include <stdio.h>
#include <windows.h>
int main(){
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hConsole, 0xC );
puts("红色文字");
SetConsoleTextAttribute(hConsole, 0xF );
puts("白色文字");
SetConsoleTextAttribute(hConsole, 2 );
puts("淡绿色文字");
return 0;
}
operation result: