c method for printing color text in the console

  • 2020-05-10 18:38:09
  • OfStack

"Hello World!" Has been written quite a few times, but all of them show white text on a console with a black background. This time I decided to write something special, making it "Hello World!" Turn it into colorful text.

The sample code is as 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 consoleHandle = 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: MarshalAs(UnmanagedType.U1)]
        public static extern bool SetConsoleTextAttribute(IntPtr consoleHandle, ushort attributes);   
    }
}

The main methods used are GetStdHandle and SetConsoleTextAttribute. The former gets a handle to the console, and the latter sets the console's text color.

The loop sets each character of the string to a different color, and displays it 1 by 1, resulting in a string of colored text.

As for the actual purpose of the code, I think it might be useful to output logs from the console. This is especially true when different types of logs are displayed prominently, such as red and yellow for error, warning, and message types, as opposed to the usual white.


Related articles: