"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