当前位置: 移动技术网 > IT编程>开发语言>c# > c#在控制台输出彩色文字的方法

c#在控制台输出彩色文字的方法

2019年07月18日  | 移动技术网IT编程  | 我要评论

“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。前者取得控制台的句柄,后者设置控制台的文字颜色。

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

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网