public
partial
class
Form1 : Form
[System.Runtime.InteropServices.DllImport(
"
kernel32.dll
"
, SetLastError =
true
)]
[
return
: System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.Bool)]
static
extern
bool
AllocConsole();
[System.Runtime.InteropServices.DllImport(
"
Kernel32
"
)]
public
static
extern
void
FreeConsole();
public
Form1()
InitializeComponent();
private
void
Form1_Load(
object
sender, EventArgs e)
AllocConsole();
//
开启控制台
通常的代码段: Console.WriteLine(“测试”);
效果显示:
创建方法类来进行输出
Shell.WriteLine("注意:启动程序...");
Shell.WriteLine("\tWritten by wuming");
Shell.WriteLine("{0}:{1}", "警告", "这是一条警告信息。");
Shell.WriteLine("{0}:{1}", "错误", "这是一条错误信息!");
Shell.WriteLine("{0}:{1}", "注意", "这是一条需要的注意信息。");
Shell.WriteLine("");
Shell.WriteLine("测试",ConsoleColor.DarkRed);
static class Shell
/// <summary>
/// 输出信息
/// </summary>
/// <param name="format"></param>
/// <param name="args"></param>
public static void WriteLine(string message, ConsoleColor GetConsoleColor)
Console.ForegroundColor = GetConsoleColor;
Console.WriteLine(@"[{0}]{1}", DateTimeOffset.Now, message);
/// <summary>
/// 输出信息
/// </summary>
/// <param name="format"></param>
/// <param name="args"></param>
public static void WriteLine(string format, params object[] args)
WriteLine(string.Format(format, args));
/// <summary>
/// 输出信息
/// </summary>
/// <param name="output"></param>
public static void WriteLine(string output)
Console.ForegroundColor = GetConsoleColor(output);
Console.WriteLine(@"[{0}]{1}", DateTimeOffset.Now, output);
/// <summary>
/// 根据输出文本选择控制台文字颜色
/// </summary>
/// <param name="output"></param>
/// <returns></returns>
private static ConsoleColor GetConsoleColor(string output)
if (output.StartsWith("警告")) return ConsoleColor.Yellow;
if (output.StartsWith("错误")) return ConsoleColor.Red;
if (output.StartsWith("注意")) return ConsoleColor.Green;
return ConsoleColor.Gray;
效果显示: