A p/invoke wrapper for SetConsoleTextAttribute -- for writing colored text to the console.
using System;
using System.Runtime.InteropServices;
internal sealed class ColorConsole
{
//
// Interface
[Flags] public enum ColorFlags:ushort
{
ForegroundBlue=1,
ForegroundGreen=2,
ForegroundRed=4,
ForegroundGray=7,
ForegroundIntense=8,
BackgroundBlue=16,
BackgroundGreen=32,
BackgroundRed=64,
BackgroundIntense=128
}
public static void Write(ColorFlags colorFlags, string text, params object[] args)
{
if (args == null)
args = new object[] { };
TrySetConsoleColor(colorFlags);
Console.Write(text,args);
TrySetConsoleColor(ColorFlags.ForegroundGray);
}
public static void WriteLine(ColorFlags colorFlags, string text, params object[] args)
{
Write(colorFlags,text+Environment.NewLine,args);
}
//
// Implementation
private ColorConsole()
{ } //noncreatable
private static void SetConsoleColor(ColorFlags colorFlags)
{
IntPtr hStdOut = Kernel32.GetStdHandle(Kernel32.StdOutputHandle);
if (hStdOut == Kernel32.InvalidHandleValue)
throw new System.ComponentModel.Win32Exception();
if (!Kernel32.SetConsoleTextAttribute(hStdOut,colorFlags))
throw new System.ComponentModel.Win32Exception();
}
private static void TrySetConsoleColor(ColorFlags colorFlags)
{
try
{
SetConsoleColor(colorFlags);
}
catch (System.ComponentModel.Win32Exception)
{ } //ok: calls will fail if stdout is redirected (eg: in VS output window)
}
[System.Security.SuppressUnmanagedCodeSecurity]
private class Kernel32
{
[DllImport("Kernel32.dll", SetLastError=true)]
internal static extern IntPtr GetStdHandle(int nStdHandle);
[DllImport("Kernel32.dll", SetLastError=true)]
internal static extern bool SetConsoleTextAttribute(IntPtr hConsoleOutput, ColorFlags wAttributes);
internal const int StdOutputHandle = -11;
internal static readonly IntPtr InvalidHandleValue = new IntPtr(-1);
}
}
