Go to c #: Change the text output color of the console

Source: Internet
Author: User
Tags knowledge base microsoft website
Document directory
  • Introduction
Link: http://support.microsoft.com/kb/319883/zh-cnintroduction

To use the foreground color and background color of the text displayed in the console windowSetConsoleTextAttributeWin32 application programming interface (API) function. This function sets the properties of characters written to the screen buffer.

When you change these attributes at runtime, the changes are valid as long as the console window is open. If it is disabled, and then the console window properties are re-opened, reset to their default values. If a program is executed from a command line in the running Console window, changes made to the text properties can be used in the console window, even if the window is opened, your program will exit. Therefore, the program should restore the original color attributes before exiting the program.

UseGetConsoleScreenBufferInfoAPI function. You can obtain the text attributes of the console window. This function is filledCONSOLE_SCREEN_BUFFER_INFOThe structure contains information about the current output buffer settings. This structureWAttributeThe parameter contains the color information of the foreground color and background color of the definition text. A possible color is a combination of red, green, and blue to create any color combination.

Step-by-step examples

  1. Create a New Visual C # console application project in Visual Studio .net or Visual Studio 2005.
  2. In Solution Explorer, right-click your project and clickAddAnd then selectAdd classAdd a new class to your program.
  3. Paste the following code example created in the class. The verification code sample replaces all existing classes in the code.

 

 OriginalColors = ConsoleInfo.wAttributes;
SetConsoleTextAttribute(hConsoleHandle, color);

 

UseResetColorMethod can be reset to the output buffer attribute of the console window captured when the program starts execution.

 

 SetConsoleTextAttribute(hConsoleHandle, OriginalColors);
Step-by-step examples

  1. Create a New Visual C # console application project in Visual Studio .net or Visual Studio 2005.
  2. In Solution Explorer, right-click your project and clickAddAnd then selectAdd classAdd a new class to your program.
  3. Paste the following code example created in the class. The verification code sample replaces all existing classes in the code.

 

Code

 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("kernel32.dll", EntryPoint="GetStdHandle", SetLastError=true,
CharSet=CharSet.Auto,
CallingConvention=CallingConvention.StdCall)]
private static extern int GetStdHandle(int nStdHandle);

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

[DllImport("kernel32.dll", EntryPoint="SetConsoleTextAttribute",
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);
}
}
}

 

4. paste the following code example to includeMainFunction class file. The verified code sample replaces all

Code

 using System;

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

 

For more information, visit the following Microsoft Website:

Console Functions
Http://msdn2.microsoft.com/en-us/library/ms682073.aspx (http://msdn2.microsoft.com/en-us/library/ms682073.aspx)

For more information, click the following article number to view the article in the Microsoft Knowledge Base:

319257 (http://support.microsoft.com/kb/319257/EN-US/) How to: Clear the console window with Visual C #. net click here to view the English version of the article: 319883
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.