How to Change Text or Background Color in a Windows Console Application

How to change text or background color in a Windows console application

Colour isn't a C++ thing, but a property of your terminal. If your terminal speaks ANSI (e.g. any Linux terminal, or DOS or Windows NT if you add DEVICE=C:\DOS\ansi.sys to your config.sys, or later Windows if you call the shell with cmd.exe /kansicon), then you can try the following gimmick:

#define ANSI_COLOR_RED     "\x1b[31m"
#define ANSI_COLOR_GREEN "\x1b[32m"
#define ANSI_COLOR_YELLOW "\x1b[33m"
#define ANSI_COLOR_BLUE "\x1b[34m"
#define ANSI_COLOR_MAGENTA "\x1b[35m"
#define ANSI_COLOR_CYAN "\x1b[36m"

#define ANSI_COLOR_BRIGHT "\x1b[1m"
#define ANSI_COLOR_RESET "\x1b[0m"

std::cout << ANSI_COLOR_RED "Hello World\n" ANSI_COLOR_RESET;

Wikipedia has a list of ANSI escape sequences.

How Can I change the background color of a text on a Console Application C#

This will help

        for (int i = 0; i < 100; i++)
{
Console.WriteLine();
string Text = "MAP" + i;
Console.SetCursorPosition((Console.WindowWidth - Text.Length) / 2, Console.CursorTop);
if (i == 0)
{
Console.BackgroundColor = ConsoleColor.White;
Console.ForegroundColor = ConsoleColor.Black;
Console.WriteLine(Text);
Console.ResetColor();
}
else
{
Console.WriteLine(Text);
}
}

See result

Custom text color in C# console application?

The list found at http://msdn.microsoft.com/en-us/library/system.console.backgroundcolor.aspx

I believe are the only supported colors in console. No hex allowed.

Black
DarkBlue
DarkGreen
DarkCyan
DarkRed
DarkMagenta
DarkYellow
Gray
DarkGray
Blue
Green
Cyan
Red
Magenta
Yellow
White

EDIT

Get the working project files off my public Repo

https://bitbucket.org/benskolnick/color-console/

But on further investigation you can do a lot of work to combine red and yellow to get orange. Follow the example here. Not going to re-post wall of code.
http://support.microsoft.com/kb/319883

That Doesn't give you access to more colors but does lead in the correct direction. You will need to do some PINVOKE work but I was easily able to get orange, or any other RGB color into console.
http://pinvoke.net/default.aspx/kernel32.SetConsoleScreenBufferInfoEx

// Copyright Alex Shvedov
// Modified by MercuryP with color specifications
// Use this code in any way you want

using System;
using System.Diagnostics; // for Debug
using System.Drawing; // for Color (add reference to System.Drawing.assembly)
using System.Runtime.InteropServices; // for StructLayout

class SetScreenColorsApp
{
[StructLayout(LayoutKind.Sequential)]
internal struct COORD
{
internal short X;
internal short Y;
}

[StructLayout(LayoutKind.Sequential)]
internal struct SMALL_RECT
{
internal short Left;
internal short Top;
internal short Right;
internal short Bottom;
}

[StructLayout(LayoutKind.Sequential)]
internal struct COLORREF
{
internal uint ColorDWORD;

internal COLORREF(Color color)
{
ColorDWORD = (uint) color.R + (((uint) color.G) << 8) + (((uint) color.B) << 16);
}

internal COLORREF(uint r, uint g, uint b)
{
ColorDWORD = r + (g << 8) + (b << 16);
}

internal Color GetColor()
{
return Color.FromArgb((int) (0x000000FFU & ColorDWORD),
(int) (0x0000FF00U & ColorDWORD) >> 8, (int) (0x00FF0000U & ColorDWORD) >> 16);
}

internal void SetColor(Color color)
{
ColorDWORD = (uint) color.R + (((uint) color.G) << 8) + (((uint) color.B) << 16);
}
}

[StructLayout(LayoutKind.Sequential)]
internal struct CONSOLE_SCREEN_BUFFER_INFO_EX
{
internal int cbSize;
internal COORD dwSize;
internal COORD dwCursorPosition;
internal ushort wAttributes;
internal SMALL_RECT srWindow;
internal COORD dwMaximumWindowSize;
internal ushort wPopupAttributes;
internal bool bFullscreenSupported;
internal COLORREF black;
internal COLORREF darkBlue;
internal COLORREF darkGreen;
internal COLORREF darkCyan;
internal COLORREF darkRed;
internal COLORREF darkMagenta;
internal COLORREF darkYellow;
internal COLORREF gray;
internal COLORREF darkGray;
internal COLORREF blue;
internal COLORREF green;
internal COLORREF cyan;
internal COLORREF red;
internal COLORREF magenta;
internal COLORREF yellow;
internal COLORREF white;
}

const int STD_OUTPUT_HANDLE = -11; // per WinBase.h
internal static readonly IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1); // per WinBase.h

[DllImport("kernel32.dll", SetLastError = true)]
private static extern IntPtr GetStdHandle(int nStdHandle);

[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool GetConsoleScreenBufferInfoEx(IntPtr hConsoleOutput, ref CONSOLE_SCREEN_BUFFER_INFO_EX csbe);

[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool SetConsoleScreenBufferInfoEx(IntPtr hConsoleOutput, ref CONSOLE_SCREEN_BUFFER_INFO_EX csbe);

// Set a specific console color to an RGB color
// The default console colors used are gray (foreground) and black (background)
public static int SetColor(ConsoleColor consoleColor, Color targetColor)
{
return SetColor(consoleColor, targetColor.R, targetColor.G, targetColor.B);
}

public static int SetColor(ConsoleColor color, uint r, uint g, uint b)
{
CONSOLE_SCREEN_BUFFER_INFO_EX csbe = new CONSOLE_SCREEN_BUFFER_INFO_EX();
csbe.cbSize = (int)Marshal.SizeOf(csbe); // 96 = 0x60
IntPtr hConsoleOutput = GetStdHandle(STD_OUTPUT_HANDLE); // 7
if (hConsoleOutput == INVALID_HANDLE_VALUE)
{
return Marshal.GetLastWin32Error();
}
bool brc = GetConsoleScreenBufferInfoEx(hConsoleOutput, ref csbe);
if (!brc)
{
return Marshal.GetLastWin32Error();
}

switch (color)
{
case ConsoleColor.Black:
csbe.black = new COLORREF(r, g, b);
break;
case ConsoleColor.DarkBlue:
csbe.darkBlue = new COLORREF(r, g, b);
break;
case ConsoleColor.DarkGreen:
csbe.darkGreen = new COLORREF(r, g, b);
break;
case ConsoleColor.DarkCyan:
csbe.darkCyan = new COLORREF(r, g, b);
break;
case ConsoleColor.DarkRed:
csbe.darkRed = new COLORREF(r, g, b);
break;
case ConsoleColor.DarkMagenta:
csbe.darkMagenta = new COLORREF(r, g, b);
break;
case ConsoleColor.DarkYellow:
csbe.darkYellow = new COLORREF(r, g, b);
break;
case ConsoleColor.Gray:
csbe.gray = new COLORREF(r, g, b);
break;
case ConsoleColor.DarkGray:
csbe.darkGray = new COLORREF(r, g, b);
break;
case ConsoleColor.Blue:
csbe.blue = new COLORREF(r, g, b);
break;
case ConsoleColor.Green:
csbe.green = new COLORREF(r, g, b);
break;
case ConsoleColor.Cyan:
csbe.cyan = new COLORREF(r, g, b);
break;
case ConsoleColor.Red:
csbe.red = new COLORREF(r, g, b);
break;
case ConsoleColor.Magenta:
csbe.magenta = new COLORREF(r, g, b);
break;
case ConsoleColor.Yellow:
csbe.yellow = new COLORREF(r, g, b);
break;
case ConsoleColor.White:
csbe.white = new COLORREF(r, g, b);
break;
}
++csbe.srWindow.Bottom;
++csbe.srWindow.Right;
brc = SetConsoleScreenBufferInfoEx(hConsoleOutput, ref csbe);
if (!brc)
{
return Marshal.GetLastWin32Error();
}
return 0;
}

public static int SetScreenColors(Color foregroundColor, Color backgroundColor)
{
int irc;
irc = SetColor(ConsoleColor.Gray, foregroundColor);
if (irc != 0) return irc;
irc = SetColor(ConsoleColor.Black, backgroundColor);
if (irc != 0) return irc;

return 0;
}
}

And then if you want to use Orange or any other color you can do a simple call to SetScreenColor

static void Main(string[] args)
{

Color screenTextColor = Color.Orange;
Color screenBackgroundColor = Color.Black;
int irc = SetScreenColorsApp.SetScreenColors(screenTextColor, screenBackgroundColor);
Debug.Assert(irc == 0, "SetScreenColors failed, Win32Error code = " + irc + " = 0x" + irc.ToString("x"));

Debug.WriteLine("LargestWindowHeight=" + Console.LargestWindowHeight + " LargestWindowWidth=" + Console.LargestWindowWidth);
Debug.WriteLine("BufferHeight=" + Console.BufferHeight + " WindowHeight=" + Console.WindowHeight + " BufferWidth=" + Console.BufferWidth + " WindowWidth=" + Console.WindowWidth);
//// these are relative to the buffer, not the screen:
//Debug.WriteLine("WindowTop=" + Console.WindowTop + " WindowLeft=" + Console.WindowLeft);
Debug.WriteLine("ForegroundColor=" + Console.ForegroundColor + " BackgroundColor=" + Console.BackgroundColor);
Console.WriteLine("Some text in a console window");
Console.BackgroundColor = ConsoleColor.Cyan;
Console.ForegroundColor = ConsoleColor.Yellow;
Debug.WriteLine("ForegroundColor=" + Console.ForegroundColor + " BackgroundColor=" + Console.BackgroundColor);
Console.Write("Press ENTER to exit...");
Console.ReadLine();

// Note: If you use SetScreenColors, the RGB values of gray and black are changed permanently for the console window.
// Using i.e. Console.ForegroundColor = ConsoleColor.Gray afterwards will switch the color to whatever you changed gray to

// It's best to use SetColor for the purpose of choosing the 16 colors you want the console to be able to display, then use
// Console.BackgroundColor and Console.ForegrondColor to choose among them.
}

How do I change the full background color of the console window in C#?

You need to clear the console window AFTER setting the colors but BEFORE you write the text...

Console.ForegroundColor = ConsoleColor.Red;
Console.BackgroundColor = ConsoleColor.Green;

Console.Clear();

Console.WriteLine("Hello World");

Console.ReadLine();

Change entire console background color (Win32 C++)

Try something like:

system("color c2");

Is it possible to change text color and background color in the console to different colors while still on the same line? C++

Yes, it is possible. The reason it isn't working for you is because your code is wrong. You never set a background color; you just manipulate the foreground color.

The source of the problem is almost certainly the fact that you're using magic numbers (0 | 15 and 5 | 0) instead of the constants that are defined in <Windows.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.

The following code works fine for me:

const HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);

// yellow on blue
SetConsoleTextAttribute(hConsole, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_INTENSITY | BACKGROUND_BLUE);
std::cout << 1;

// blue on bright green
SetConsoleTextAttribute(hConsole, FOREGROUND_BLUE | BACKGROUND_GREEN | BACKGROUND_INTENSITY);
std::cout << 2;

// reset to black on white
SetConsoleTextAttribute(hConsole, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY);
std::cout << std::endl;

Here's a screenshot of my console window as proof that it works. (But note that my console's colors have been customized to the Tango theme, so yours will probably use slightly different colors.)

Sample Image

I recommend making life easier on yourself by defining an enum:

enum ConsoleColors
{
BlackFore = 0,
MaroonFore = FOREGROUND_RED,
GreenFore = FOREGROUND_GREEN,
NavyFore = FOREGROUND_BLUE,
TealFore = FOREGROUND_GREEN | FOREGROUND_BLUE,
OliveFore = FOREGROUND_RED | FOREGROUND_GREEN,
PurpleFore = FOREGROUND_RED | FOREGROUND_BLUE,
GrayFore = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE,
SilverFore = FOREGROUND_INTENSITY,
RedFore = FOREGROUND_INTENSITY | FOREGROUND_RED,
LimeFore = FOREGROUND_INTENSITY | FOREGROUND_GREEN,
BlueFore = FOREGROUND_INTENSITY | FOREGROUND_BLUE,
AquaFore = FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_BLUE,
YellowFore = FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN,
FuchsiaFore = FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_BLUE,
WhiteFore = FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE,

BlackBack = 0,
MaroonBack = BACKGROUND_RED,
GreenBack = BACKGROUND_GREEN,
NavyBack = BACKGROUND_BLUE,
TealBack = BACKGROUND_GREEN | BACKGROUND_BLUE,
OliveBack = BACKGROUND_RED | BACKGROUND_GREEN,
PurpleBack = BACKGROUND_RED | BACKGROUND_BLUE,
GrayBack = BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE,
SilverBack = BACKGROUND_INTENSITY,
RedBack = BACKGROUND_INTENSITY | BACKGROUND_RED,
LimeBack = BACKGROUND_INTENSITY | BACKGROUND_GREEN,
BlueBack = BACKGROUND_INTENSITY | BACKGROUND_BLUE,
AquaBack = BACKGROUND_INTENSITY | BACKGROUND_GREEN | BACKGROUND_BLUE,
YellowBack = BACKGROUND_INTENSITY | BACKGROUND_RED | BACKGROUND_GREEN,
FuchsiaBack = BACKGROUND_INTENSITY | BACKGROUND_RED | BACKGROUND_BLUE,
WhiteBack = BACKGROUND_INTENSITY | BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE,
};

and then set colors like this:

SetConsoleTextAttribute(hConsole, ConsoleColors::BlackBack |
ConsoleColors::RedFore));

Change background color of C++ console app

You asked:

how to use colors other than green, red, blue?

You may combine the flags to create new colors:

An application can combine the foreground and background constants to
achieve different colors. For example, the following combination
results in bright cyan text on a blue background.

FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_INTENSITY |
BACKGROUND_BLUE

If no background constant is specified, the background is black, and
if no foreground constant is specified, the text is black. For
example, the following combination produces black text on a white
background.

BACKGROUND_BLUE | BACKGROUND_GREEN | BACKGROUND_RED

Beyond that, you may set colors individually on each char and/or modify the screen buffer attributes:

Each screen buffer character cell stores the color attributes for the
colors used in drawing the foreground (text) and background of that
cell. An application can set the color data for each character cell
individually, storing the data in the Attributes member of the
CHAR_INFO structure for each cell. The current text attributes of each
screen buffer are used for characters subsequently written or echoed
by the high-level functions.

An application can use GetConsoleScreenBufferInfo to determine the
current text attributes of a screen buffer and the
SetConsoleTextAttribute function to set the character attributes.
Changing a screen buffer's attributes does not affect the display of
characters previously written. These text attributes do not affect
characters written by the low-level console I/O functions (such as the
WriteConsoleOutput or WriteConsoleOutputCharacter function), which
either explicitly specify the attributes for each cell that is written
or leave the attributes unchanged.

For documentation and example see: https://learn.microsoft.com/en-us/windows/console/using-the-high-level-input-and-output-functions

Alternating Console Background Color - C#

The background color is only applied to columns where you actually print a value. You can print to every column by space-filling the entire row:

var width = Console.WindowWidth;
Console.BackgroundColor = System.ConsoleColor.DarkRed;
Console.WriteLine("{0, -" + width + "}", "TestRed");

This will print the entire row with a dark red background color.



Related Topics



Leave a reply



Submit