如何在C#控制台程序中对输出文本使用颜色

C#控制台程序还是很常用的, 尤其是开发Server程序的时候, 对于Server出现的各种提示信息使用不同颜色输出, 对用户将是一个很好的提示. 比如错误使用红色输出, 警告使用黄色输出, 而绿色则表示正常等等. 下面是我实现的一个简单的带颜色控制台类.

ColorConsole.cs:
[code=’c#’]
public enum Color
{
Black = 0x00000000,
DarkBlue = 0x00000001,
DarkGreen = 0x00000002,
DarkCyan = 0x00000003,
DarkRed = 0x00000004,
DarkPink = 0x00000005,
DarkYellow = 0x00000006,
DarkWhite = 0x00000007,
Gray = 0x00000008,
Blue = 0x00000009,
Green = 0x000000A,
Cyan = 0x0000000B,
Red = 0x0000000C,
Pink = 0x0000000D,
Yellow = 0x0000000E,
White = 0x0000000F
}

class ColorConsole
{
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);

[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 ColorConsole()
{
ConsoleInfo = new CONSOLE_SCREEN_BUFFER_INFO();
ConsoleOutputLocation = new COORD();
hConsoleHandle = GetStdHandle(STD_OUTPUT_HANDLE);
GetConsoleScreenBufferInfo(hConsoleHandle, ref ConsoleInfo);
OriginalColors = ConsoleInfo.wAttributes;
}

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

public void TextColor(Color textColor, Color backColor)
{
SetConsoleTextAttribute(hConsoleHandle, (int)textColor + (int)backColor * 16);
}

public void ResetColor()
{
SetConsoleTextAttribute(hConsoleHandle, OriginalColors);
}
}
[/code]

TestCase:
[code=’c#’]
class Program
{
static void Main(string[] args)
{
ColorConsole cc = new ColorConsole();
cc.TextColor(Color.Red, Color.Gray);
Console.WriteLine(“Server Stopped.”);
}
}
[/code]

参考资料:

[Microsoft Support] 如何通过使用 VisualC # 更改前景颜色和背景颜色控制台窗口中的文本:
http://support.microsoft.com/kb/319883/zh-cn

推荐文章

发表评论