zoukankan      html  css  js  c++  java
  • 在控制台输出彩色的Hello World!

    “Hello World!”的程序写过不少,不过都是在黑色背景的控制台上显示白色的文字。这次决定写点特别的,让“Hello World!”变成彩色的文字。

    示例代码如下:

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

    主要用到的方法是GetStdHandle与SetConsoleTextAttribute。前者取得控制台的句柄,后者设置控制台的文字颜色。

    循环语句中将字符串的每个字符设置为不同的颜色,逐一显示出来,最终成为一串彩色的文字。

    至于代码的实际用途吗,我想在控制台上输出日志的时候可能会有作用。尤其是要醒目地显示不同类型日志的场合下,比如可以将错误,警告和信息类型的日志分别用红色,黄色与通常的白色区别开来。

    原文同步发布于我的个人博客

  • 相关阅读:
    python学习
    androidandroid中的通过网页链接打开本地app
    Android自定义View之绘制虚线
    Backbone学习记录(3)
    Backbone学习记录(2)
    Backbone学习记录(1)
    网络时间轴中竖线的含义
    控制台笔记
    css hack 笔记
    Fiddler学习笔记
  • 原文地址:https://www.cnblogs.com/sjyforg/p/2958197.html
Copyright © 2011-2022 走看看