Console color output and console output

Source: Internet
Author: User

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 ();

 

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.