using System; using System.IO; using System.Runtime.InteropServices; namespace ClassLibrary1 { static class ConsoleShow { static bool bFlag = false; public static void Log(string str) { if (!bFlag) { bFlag = true; AllocConsole(); // stdout's handle seems to always be equal to 7 IntPtr defaultStdout = new IntPtr(7); IntPtr currentStdout = GetStdHandle(StdOutputHandle); if (currentStdout != defaultStdout) // reset stdout SetStdHandle(StdOutputHandle, defaultStdout); // reopen stdout TextWriter writer = new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = true }; Console.SetOut(writer); } WriteLine(str); FileLog.Log(str); } /// /// 启动控制台 /// /// [DllImport("kernel32.dll")] public static extern bool AllocConsole(); /// /// 释放控制台 /// /// [DllImport("kernel32.dll")] public static extern bool FreeConsole(); // P/Invoke required: private const UInt32 StdOutputHandle = 0xFFFFFFF5; [DllImport("kernel32.dll")] private static extern IntPtr GetStdHandle(UInt32 nStdHandle); [DllImport("kernel32.dll")] private static extern void SetStdHandle(UInt32 nStdHandle, IntPtr handle); /// /// 输出信息 /// /// /// public static void WriteLine(string format, params object[] args) { WriteLine(string.Format(format, args)); } /// /// 输出信息 /// /// public static void WriteLine(string output) { Console.ForegroundColor = GetConsoleColor(output); Console.WriteLine(@"[{0}]{1}", DateTimeOffset.Now, output); } /// /// 根据输出文本选择控制台文字颜色 /// /// /// 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; } } }