Win32API コンソールの前景色、背景色を設定する SetConsoleTextAttribute
コンソールの前景色、背景色を設定するには、SetConsoleTextAttribute関数を用いる。
SetConsoleTextAttributeのプロトタイプ
BOOL SetConsoleTextAttribute( HANDLE hConsoleOutput, // コンソールスクリーンバッファのハンドル WORD wAttributes // テキストと背景の色 );
wAttributes の値は wincon.h に定義されている以下のフラグの論理和により設定する
#define FOREGROUND_BLUE 0x0001 // text color contains blue. #define FOREGROUND_GREEN 0x0002 // text color contains green. #define FOREGROUND_RED 0x0004 // text color contains red. #define FOREGROUND_INTENSITY 0x0008 // text color is intensified. #define BACKGROUND_BLUE 0x0010 // background color contains blue. #define BACKGROUND_GREEN 0x0020 // background color contains green. #define BACKGROUND_RED 0x0040 // background color contains red. #define BACKGROUND_INTENSITY 0x0080 // background color is intensified. #define COMMON_LVB_LEADING_BYTE 0x0100 // Leading Byte of DBCS #define COMMON_LVB_TRAILING_BYTE 0x0200 // Trailing Byte of DBCS #define COMMON_LVB_GRID_HORIZONTAL 0x0400 // DBCS: Grid attribute: top horizontal. #define COMMON_LVB_GRID_LVERTICAL 0x0800 // DBCS: Grid attribute: left vertical. #define COMMON_LVB_GRID_RVERTICAL 0x1000 // DBCS: Grid attribute: right vertical. #define COMMON_LVB_REVERSE_VIDEO 0x4000 // DBCS: Reverse fore/back ground attribute. #define COMMON_LVB_UNDERSCORE 0x8000 // DBCS: Underscore. #define COMMON_LVB_SBCSDBCS 0x0300 // SBCS or DBCS flag.
使用例
前景色を赤色に、背景色を緑色に設定する。#include <windows.h> #include <stdio.h> int main() { SetConsoleTextAttribute( GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY | FOREGROUND_RED | BACKGROUND_GREEN); printf("Hello, World!\n"); return 0; }