The use of the Console.Write function in WPF to print information is meaningless because there is no window for its output characters. For the desktop program, this is very reasonable, but sometimes in order to facilitate debugging, in the process of writing a program to print information to the programmer is still necessary, using the Windows API, at the time of debug to open a console window for information printing display.
Create a Management class
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;} }///Creates a new console instance if the process is not attached to a console already. public static void Show () {#if DEBUG if (! Hasconsole) {allocconsole (); Invalidateoutanderror (); } #endif}///IF The process has a console attached to it, it'll be detached and no longer visible. Writing to the System.Console are still possible, but no output would be shown. 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); }}
Call where needed: Consolemanager.show ();//Opening the console window
WPF uses Console.Write to print information to the console window