Microsoft KB Archive/319883

= How to change foreground colors and background colors of text in a Console window by using Visual C# =

Article ID: 319883

Article Last Modified on 11/26/2007

-

APPLIES TO


 * Microsoft Visual C# .NET 2002 Standard Edition
 * Microsoft Visual C# 2005 Express Edition

-



This article was previously published under Q319883



For a Microsoft Visual Basic .NET version of this article, see 319234.

This article refers to the following Microsoft .NET Framework Class Library namespace:
 * System.Runtime.InteropServices

IN THIS TASK
SUMMARY
 * Introduction
 * Step-by-Step Example
 * Troubleshooting

REFERENCES



SUMMARY
This step-by-step article describes how to change the foreground and background colors of the text that is written to the Console window by using Visual C#.

This article describes how to save the original settings of the Console window as the program starts, how to modify the color settings, and how to restore the colors to their original values as the program quits.

back to the top

Introduction
To change the foreground and background colors of text that the Console window displays, use the SetConsoleTextAttribute Win32 application programming interface (API) function. This function sets the attributes of the characters that are written to the screen buffer.

When you change these attributes at run time, the changes are valid for as long as the Console window is open. If you close and reopen the Console window, the attributes are reset to their default values. If you execute the program from a command line in a Console window that is already running, changes that you make to the text attributes are valid for that Console window for as long as the window is open, even after your program quits. Therefore, an program should restore the original color attributes before the program quits.

You can obtain the text attributes of the Console window by using the GetConsoleScreenBufferInfo API function. This function fills an instance of the CONSOLE_SCREEN_BUFFER_INFO structure with information about the current output buffer settings. The wAttribute parameter of this structure contains the color information that defines the foreground and background colors of the text. The possible colors are any color combination that can be created by combining red, green, and blue. OriginalColors = ConsoleInfo.wAttributes; SetConsoleTextAttribute(hConsoleHandle, color); You can use the ResetColor method to reset the output buffer attributes of the Console window to the original values that are captured when the program begins its execution. SetConsoleTextAttribute(hConsoleHandle, OriginalColors); back to the top

Step-by-Step Example
 In Visual Studio .NET or Visual Studio 2005, create an new Visual C# Console Application project. In Solution Explorer, right-click your project, click Add, and then select Add Class to add a new class to your program.  Paste the following sample code in the class that is created. Verify that the sample code replaces all of existing the code in the class. using System; using System.Runtime.InteropServices;

namespace ConsoleColor {     /// Summary description for Class2. public class Class2 {        private int hConsoleHandle; private COORD ConsoleOutputLocation; private CONSOLE_SCREEN_BUFFER_INFO ConsoleInfo; private int OriginalColors;

private const int STD_OUTPUT_HANDLE = -11;

[DllImport(&quot;kernel32.dll&quot;, EntryPoint=&quot;GetStdHandle&quot;, SetLastError=true,                        CharSet=CharSet.Auto,                         CallingConvention=CallingConvention.StdCall)] private static extern int GetStdHandle(int nStdHandle);

[DllImport(&quot;kernel32.dll&quot;, EntryPoint=&quot;GetConsoleScreenBufferInfo&quot;,                        SetLastError=true, CharSet=CharSet.Auto,                         CallingConvention=CallingConvention.StdCall)] private static extern int GetConsoleScreenBufferInfo(int hConsoleOutput,                        ref CONSOLE_SCREEN_BUFFER_INFO lpConsoleScreenBufferInfo);

[DllImport(&quot;kernel32.dll&quot;, EntryPoint=&quot;SetConsoleTextAttribute&quot;,                        SetLastError=true, CharSet=CharSet.Auto,                         CallingConvention=CallingConvention.StdCall)] private static extern int SetConsoleTextAttribute(int hConsoleOutput,                                int wAttributes); public enum Foreground {                     Blue = 0x00000001, Green = 0x00000002, Red = 0x00000004, Intensity = 0x00000008 }

public enum Background {           Blue = 0x00000010, Green = 0x00000020, Red = 0x00000040, Intensity = 0x00000080 }

[StructLayout(LayoutKind.Sequential)] private struct COORD {           short X;            short Y;         } [StructLayout(LayoutKind.Sequential)] private struct SMALL_RECT {           short Left; short Top; short Right; short Bottom; }

[StructLayout(LayoutKind.Sequential)] private struct CONSOLE_SCREEN_BUFFER_INFO {           public COORD dwSize; public COORD dwCursorPosition; public int wAttributes; public SMALL_RECT srWindow; public COORD dwMaximumWindowSize; }

// Constructor. public Class2 {           ConsoleInfo = new CONSOLE_SCREEN_BUFFER_INFO; ConsoleOutputLocation = new COORD; hConsoleHandle = GetStdHandle(STD_OUTPUT_HANDLE); GetConsoleScreenBufferInfo(hConsoleHandle, ref ConsoleInfo); OriginalColors = ConsoleInfo.wAttributes; }

public void TextColor(int color) {           SetConsoleTextAttribute(hConsoleHandle, color); }        public void ResetColor {           SetConsoleTextAttribute(hConsoleHandle, OriginalColors); }     }   }                      Paste the following sample code in the class file that contains the Main function. Verify that the sample code replaces all of the existing code in the file. using System;

namespace ConsoleColor {     class Class1 {        [STAThread] static void Main(string[] args) {           Class2 TextChange = new Class2; Console.WriteLine(&quot;Original Colors&quot;); Console.WriteLine(&quot;Press Enter to Begin&quot;); Console.ReadLine; TextChange.TextColor((int)Class2.Foreground.Green +                                (int)Class2.Foreground.Intensity); Console.WriteLine(&quot;THIS TEXT IS GREEN&quot;); Console.WriteLine(&quot;Press Enter to change colors again&quot;); Console.ReadLine; TextChange.TextColor((int)Class2.Foreground.Red +                                (int)Class2.Foreground.Blue +                                 (int)Class2.Foreground.Intensity); Console.WriteLine(&quot;NOW THE TEXT IS PURPLE&quot;); Console.WriteLine(&quot;Press Enter to change colors again&quot;); Console.ReadLine; TextChange.TextColor((int)Class2.Foreground.Blue +                                (int)Class2.Foreground.Intensity +                                 (int)Class2.Background.Green +                                 (int)Class2.Background.Intensity); Console.WriteLine(&quot;NOW THE TEXT IS BLUE AND BACKGROUND OF IT IS GREEN&quot;); Console.WriteLine(&quot;Press Enter change everything back to normal&quot;); Console.ReadLine; TextChange.ResetColor; Console.WriteLine(&quot;Back to Original Colors&quot;); Console.WriteLine(&quot;Press Enter to Terminate&quot;); Console.ReadLine; }     }   }                     Press F5 to compile and then run the program.

back to the top

Troubleshooting
If you experience problems, verify that you are passing a valid value as the parameter for the TextColor method. To create a valid value, combine the values that you obtain from the Foreground and Background enumerations as defined in the class.

back to the top

