天天看點

C#更改控制台文本的前景色和背景色

關鍵字:C# NET 控制台 前景色 背景色

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. 

To change the foreground and background colors of text that the Console window displays, use the SetConsoleTextAttributeWin32 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. ThewAttribute 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.

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.

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.

  4. 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.