控制台彩色输出
大概已经习惯了黑底白字的控制台程序了:今天贴一下实现控制台输出彩色文字及背景的最简单方法!
方法1:
1.设置控制台背景颜色;
2设置控制台前景色;
3调用WriteLine(XXX)方法输出内容
4.调用ResetColor()方法恢复控制台
下面是一个简单实例:
class Program
{
[MTAThread]
static void Main(string[] args)
{
Console.BackgroundColor = ConsoleColor.Green;
Console.ForegroundColor = ConsoleColor.Red;
WriteLine("测试输出绿底红字");
Console.ResetColor();
Console.BackgroundColor = Console.BackgroundColor;
Console.ForegroundColor = ConsoleColor.Blue;
WriteLine("测试输出蓝色字");
Console.ResetColor();
}
}
方法2.调用Win32API:
[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);//设置属性
const UInt32 STD_OUTPUT_HANDLE = unchecked((UInt32)(-11));
IntPtr consoleHandle = GetStdHandle(STD_OUTPUT_HANDLE);
string s = "Hello World!";
for (int i = 0; i < s.Length; i++)
{
SetConsoleTextAttribute(consoleHandle, (ushort)(i + 1));
Console.Write(s[i]);
}
Console.ReadLine();