Output the colorful Hello world in the console!

Source: Internet
Author: User

"Hello world !" OfProgramI have written a lot, but they all show white text on the black background console. This time I decided to write something special and let "Hello world !" Color text.

ExampleCodeAs follows:

 Using  System;  Using  System. runtime. interopservices; [Assembly: clscompliant (  True  )]  Namespace  Colorconsole {  Public   Sealed   Class  Helloworld { Private  Helloworld (){}  Public   Static   Void  Main (){  Const Uint32 std_output_handle = Unchecked (Uint32 )(- 11  ); Intptr lelehandle = Nativemethods. getstdhandle (std_output_handle );  String S = " Hello world!  "  ;  For ( Int I = 0 ; I <S. length; I ++ ) {Nativemethods. setconsoletextattribute (consolehandle ,(  Ushort ) (I + 1  ); Console. Write (s [I]);} console. Readline ();}}  Class  Nativemethods { Private  Nativemethods () {} [dllimport (  "  Kernel32.dll  " , Setlasterror = True , Charset = Charset. Auto)]  Public   Static   Extern  Intptr getstdhandle (uint32 type); [dllimport (  "  Kernel32.dll  " , Setlasterror =True , Charset = Charset. Auto)] [  Return  : Financialas (unmanagedtype. U1)]  Public   Static   Extern   Bool Setconsoletextattribute (intptr consolehandle, Ushort  Attributes );}} 

The main methods used are getstdhandle and setconsoletextattribute. The former gets the handle of the console, and the latter sets the text color of the console.

In the loop statement, each character of the string is set to a different color, which is displayed one by one, and eventually becomes a string of colored text.

As for the actual usage of the code, I think it may be useful to output logs on the console. Especially when you need to clearly display different types of logs, for example, you can use red to indicate errors, warnings, and information types respectively.

the original text is published on my blog

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.