Dave's Brain

Browse - Programming Tips - How do I change the color of the text in a Windows console

Date: 2010apr26
OS: Windows
Language: C/C++

Q.  How do I change the color of the text in a Windows console
without affecting anything else?

A.  Here is a function called SetTextColor().

// Pass one of these values to SetTextColor() typedef enum { FG_RED = FOREGROUND_RED, FG_GREEN = FOREGROUND_GREEN, FG_BLUE = FOREGROUND_BLUE, FG_YELLOW = FG_RED | FG_GREEN, FG_MAGENTA = FG_RED | FG_BLUE, FG_CYAN = FG_BLUE | FG_GREEN, FG_WHITE = FG_RED | FG_GREEN | FG_BLUE, FG_BLACK = 0 } FG_COLOR; BOOL SetTextColor(const FG_COLOR color) { HANDLE hStdout = GetStdHandle(STD_OUTPUT_HANDLE); CONSOLE_SCREEN_BUFFER_INFO info; GetConsoleScreenBufferInfo(hStdout, &info); info.wAttributes &= ~FG_WHITE; // Turn off existing text colors info.wAttributes |= color; return SetConsoleTextAttribute(hStdout, info.wAttributes); } void ExampleUse() { SetTextColor(FG_CYAN); }

Add a comment

Sign in to add a comment
Copyright © 2008-2018, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.