Console color output and console output
I am probably used to the console program with black and white characters: Today I am posting the simplest method to output color text and background on the console!
Method 1:
1. Set the background color of the console;
2. Set the foreground color of the console;
3. Call the WriteLine (XXX) method to output the content.
4. Call ResetColor () to restore the Console
The following is a simple example:
Class Program
{
[MTAThread]
Static void Main (string [] args)
{
Console. BackgroundColor = ConsoleColor. Green;
Console. ForegroundColor = ConsoleColor. Red;
WriteLine ("test output green background Red Letter ");
Console. ResetColor ();
Console. BackgroundColor = Console. BackgroundColor;
Console. ForegroundColor = ConsoleColor. Blue;
WriteLine ("blue words for test output ");
Console. ResetColor ();
}
}
Method 2. Call Win32API:
[DllImport ("Kernel32.dll", SetLastError = true, CharSet = CharSet. Auto)]
Public static extern IntPtr GetStdHandle (UInt32 type); // get the handle
[DllImport ("Kernel32.dll", SetLastError = true, CharSet = CharSet. Auto)]
[Return: financialas (UnmanagedType. U1)]
Public static extern bool SetConsoleTextAttribute (IntPtr consoleHandle, ushort attributes); // you can specify attributes.
Const UInt32 STD_OUTPUT_HANDLE = unchecked (UInt32) (-11 ));
IntPtr consoleHandle = GetStdHandle (STD_OUTPUT_HANDLE );
String s = "Hello World! ";
For (int I = 0; I <s. Length; I ++)
{
SetConsoleTextAttribute (consoleHandle, (ushort) (I + 1 ));
Console. Write (s [I]);
}
Console. ReadLine ();