C# 控制台应用程序输出颜色字体[更正版]

首先感谢院子里的“yanxinchen”,之前的方法是通过c#调用系统api实现的,相比之下我的有点画蛇添足了,哈哈。

最佳解决方案的代码:

static void Main(string[] args)
{
    Console.ForegroundColor = ConsoleColor.Green;
    Console.WriteLine("Hello, color text!");
    Console.ForegroundColor = ConsoleColor.Red;
    Console.WriteLine("Hello, color text!");
    Console.ReadKey();
}

效果如图:

=================================================================================

我之前的代码如下(已过时):

控制台应用程序字体本身不能输出带颜色的字体,所有就需要调用系统的api实现,下面是一个封装好的类,另赋调用的方法,使用起来很方便,效果如图:

封装调用系统api的类ConsoleColor.cs代码如下:

using System.Runtime.InteropServices;

namespace Test
{
    /// Summary description for ConsoleColor.
    public class ConsoleColor
    {
        private int hConsoleHandle;
        private COORD ConsoleOutputLocation;
        private CONSOLE_SCREEN_BUFFER_INFO ConsoleInfo;
        private int OriginalColors;

        private const int STD_OUTPUT_HANDLE = -11;

        [DllImport("kernel32.dll", EntryPoint = "GetStdHandle", SetLastError = true,
                        CharSet = CharSet.Auto,
                        CallingConvention = CallingConvention.StdCall)]
        private static extern int GetStdHandle(int nStdHandle);

        [DllImport("kernel32.dll", EntryPoint = "GetConsoleScreenBufferInfo",
                        SetLastError = true, CharSet = CharSet.Auto,
                        CallingConvention = CallingConvention.StdCall)]
        private static extern int GetConsoleScreenBufferInfo(int hConsoleOutput,
                         ref CONSOLE_SCREEN_BUFFER_INFO lpConsoleScreenBufferInfo);

        [DllImport("kernel32.dll", EntryPoint = "SetConsoleTextAttribute",
                        SetLastError = true, CharSet = CharSet.Auto,
                        CallingConvention = CallingConvention.StdCall)]
        private static extern int SetConsoleTextAttribute(int hConsoleOutput,
                                 int wAttributes);

        public enum Foreground
        {
            Blue = 0x00000001,
            Green = 0x00000002,
            Red = 0x00000004,
            Intensity = 0x00000008
        }

        public enum Background
        {
            Blue = 0x00000010,
            Green = 0x00000020,
            Red = 0x00000040,
            Intensity = 0x00000080
        }

        [StructLayout(LayoutKind.Sequential)]
        private struct COORD
        {
            short X;
            short Y;
        }

        [StructLayout(LayoutKind.Sequential)]
        private struct SMALL_RECT
        {
            short Left;
            short Top;
            short Right;
            short Bottom;
        }

        [StructLayout(LayoutKind.Sequential)]
        private struct CONSOLE_SCREEN_BUFFER_INFO
        {
            public COORD dwSize;
            public COORD dwCursorPosition;
            public int wAttributes;
            public SMALL_RECT srWindow;
            public COORD dwMaximumWindowSize;
        }

        // Constructor.
        public ConsoleColor()
        {
            ConsoleInfo = new CONSOLE_SCREEN_BUFFER_INFO();
            ConsoleOutputLocation = new COORD();
            hConsoleHandle = GetStdHandle(STD_OUTPUT_HANDLE);
            GetConsoleScreenBufferInfo(hConsoleHandle, ref ConsoleInfo);
            OriginalColors = ConsoleInfo.wAttributes;
        }

        public void TextColor(int color)
        {
            SetConsoleTextAttribute(hConsoleHandle, color);
        }

        public void ResetColor()
        {
            SetConsoleTextAttribute(hConsoleHandle, OriginalColors);
        }
    }
}

在Main方法的调用代码如下:

ConsoleColor TextChange = new ConsoleColor();
Console.WriteLine("Original Colors");
Console.WriteLine("Press Enter to Begin");
Console.ReadLine();
TextChange.TextColor((int)ConsoleColor.Foreground.Green +
                     (int)ConsoleColor.Foreground.Intensity);
Console.WriteLine("THIS TEXT IS GREEN");
Console.WriteLine("Press Enter to change colors again");
Console.ReadLine();
TextChange.TextColor((int)ConsoleColor.Foreground.Red +
                     (int)ConsoleColor.Foreground.Blue +
                     (int)ConsoleColor.Foreground.Intensity);
Console.WriteLine("NOW THE TEXT IS PURPLE");
Console.WriteLine("Press Enter to change colors again");
Console.ReadLine();
TextChange.TextColor((int)ConsoleColor.Foreground.Blue +
                     (int)ConsoleColor.Foreground.Intensity +
                     (int)ConsoleColor.Background.Green +
                     (int)ConsoleColor.Background.Intensity);
Console.WriteLine("NOW THE TEXT IS BLUE AND BACKGROUND OF IT IS GREEN");
Console.WriteLine("Press Enter change everything back to normal");
Console.ReadLine();
TextChange.ResetColor();
Console.WriteLine("Back to Original Colors");
Console.WriteLine("Press Enter to Terminate");
Console.ReadLine();

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏c#开发者

about store RecordField submit emptystring issue

operate screenshot When click save button submit to change,trace store before...

3587
来自专栏c#开发者

XML Encryption in .Net

XML Encryption in .Net One of the new features being introduced with the Whidbey...

4637
来自专栏菩提树下的杨过

利用ActiveX实现web页面设置本地默认打印机、纸张大小

通常web技术无法设置本地计算机的默认打印机,包括用代码设置纸张大小,如果业务系统中真遇到这种需求,只能通过其它辅助手段(比如ActiveX)实现。下面这段代码...

2791
来自专栏从零开始的linux

linux基础命令6

tr命令 # tr 'a-z' 'A-Z' < /etc/fstab # # /ETC/FSTAB # CREATED BY ANACONDA ON THU ...

2927
来自专栏闻道于事

js登录滑动验证,不滑动无法登陆

js的判断这里是根据滑块的位置进行判断,应该是用一个flag判断 <%@ page language="java" contentType="text/html...

1.2K8
来自专栏xingoo, 一个梦想做发明家的程序员

使用计时器-方法2

第一种方法 是把WM_TIMER消息发送给正常的窗口过程。 第二种方法 是 自己让 windows把计时器消息发送给程序中的另一个窗口过程 回调函数: VOID...

2219
来自专栏小鹏的专栏

ubuntu下C++如何调用python程序,gdb调试C++代码

Linux下gdb调试C++代码:http://jingyan.baidu.com/article/acf728fd464984f8e410a369.html ...

3239
来自专栏程序你好

在WPF桌面程序中使用ECharts展示图表

2683
来自专栏PPV课数据科学社区

【学习】七天搞定SAS(三):基本模块调用

搞定基本的函数之后,开始鼓捣SAS里面的模型。也就是说,要开始写PROC了。说实话,越学SAS,越觉得SAS像Stata...无论是从输出的样式,还是语法。好不...

3325
来自专栏WOLFRAM

by 落霜枫舞

1563

扫码关注云+社区

领取腾讯云代金券