This is what I use to add the console to applications when I've needed it:
#region Console support
[System.Runtime.InteropServices.DllImport("Kernel32")]
public static extern void AllocConsole();
[System.Runtime.InteropServices.DllImport("Kernel32")]
public static extern void FreeConsole();
#endregion
When we need to turn it on, we can call AllocConsole(), and likewise FreeConsole() when we want to turn it back off.
As well, I created/use the following to write to the console with color:
/// <summary>
/// Writes to the Console. Does not terminate line, subsequent write is on right of same line.
/// </summary>
/// <param name="color">The color that you want to write to the line with.</param>
/// <param name="text">The text that you want to write to the console.</param>
public static void ColoredConsoleWrite(ConsoleColor color, string text)
{
ConsoleColor originalColor = Console.ForegroundColor;
Console.ForegroundColor = color;
Console.Write(text);
Console.ForegroundColor = originalColor;
}
/// <summary>
/// Writes to the Console. Terminates line, subsequent write goes to new line.
/// </summary>
/// <param name="color">The color that you want to write to the line with.</param>
/// <param name="text">The text that you want to write to the console.</param>
public static void ColoredConsoleWriteLine(ConsoleColor color, string text)
{
ConsoleColor originalColor = Console.ForegroundColor;
Console.ForegroundColor = color;
Console.WriteLine(text);
Console.ForegroundColor = originalColor;
}
Example usage:
#region User Check
Console.Write("User: {0} ... ", Environment.UserName);
if (validUser(Environment.UserName).Equals(false))
{
ColoredConsoleWrite(ConsoleColor.Red, "BAD!");
Console.WriteLine(" - Making like a tree, and getting out of here!");
Environment.Exit(0);
}
ColoredConsoleWrite(ConsoleColor.Green, "GOOD!"); Console.WriteLine(" - Continue on!");
#endregion
Valid user output with "GOOD!" being in Green text:
User: Chase.Ring ... GOOD! - Continue on!
Invalid user output with "BAD!" being in Red text:
User: Not.Chase.Ring ... BAD! - Making like a tree, and getting out of here!