1. 程式人生 > >WPF 使用Console.Write打印信息到控制臺窗口中

WPF 使用Console.Write打印信息到控制臺窗口中

ble sco urn and ati debug tin private invalid

WPF中使用Console.Write函數來打印信息是沒有意義的,因為並沒有給其輸出字符的窗口。對於桌面程序來說,這是十分合理的,然而有時為了方便調試,在程序編寫過程中打印出信息給程序員看還是必要的,利用Windows的API,在DEBUG的時候打開一個控制臺窗口以供信息打印顯示。

創建一個管理類

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 will be detached and no longer visible. Writing to the System.Console is still possible, but no output will 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);
    }
}

  在需要的地方調用: ConsoleManager.Show();//打開控制臺窗口

WPF 使用Console.Write打印信息到控制臺窗口中