在实际调用任何Console.Write方法之前,您必须手动创建一个Console窗口。这将使控制台正常运行,而无需更改项目类型(WPF应用程序将无法使用)。
这是一个完整的源代码示例,它说明ConsoleManager类的外观,以及如何使用它来启用/禁用控制台,而与项目类型无关。
在下面的类中,您只需要
ConsoleManager.Show()在调用
Console.Write…
[SuppressUnmanagedCodeSecurity]public static class ConsoleManager{ private const string Kernel32_DllName = "kernel32.dll"; [Dllimport(Kernel32_DllName)] private static extern bool AllocConsole(); [Dllimport(Kernel32_DllName)] private static extern bool FreeConsole(); [Dllimport(Kernel32_DllName)] private static extern IntPtr GetConsoleWindow(); [Dllimport(Kernel32_DllName)] private static extern int GetConsoleOutputCP(); public static bool HasConsole { get { return GetConsoleWindow() != IntPtr.Zero; } } /// <summary> /// Creates a new console instance if the process is not attached to a console already. /// </summary> public static void Show() { //#if DEBUG if (!HasConsole) { AllocConsole(); InvalidateOutAndError(); } //#endif } /// <summary> /// If the process has a console attached to it, it will be detached and no longer visible. Writing to the System.Console is still possible, but no output will be shown. /// </summary> public static void Hide() { //#if DEBUG if (HasConsole) { SetOutAndErrorNull(); FreeConsole(); } //#endif } public static void Toggle() { if (HasConsole) { Hide(); } else { Show(); } } static void InvalidateOutAndError() { Type type = typeof(System.Console); System.Reflection.FieldInfo _out = type.GetField("_out", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic); System.Reflection.FieldInfo _error = type.GetField("_error", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic); System.Reflection.MethodInfo _InitializeStdOutError = type.GetMethod("InitializeStdOutError", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic); Debug.Assert(_out != null); Debug.Assert(_error != null); Debug.Assert(_InitializeStdOutError != null); _out.SetValue(null, null); _error.SetValue(null, null); _InitializeStdOutError.Invoke(null, new object[] { true }); } static void SetOutAndErrorNull() { Console.SetOut(TextWriter.Null); Console.SetError(TextWriter.Null); }}


