隐藏并再次显示后更改控制台的颜色

时间:2019-04-24 14:24:16

标签: c# wpf colors console

有了代码,我在这个线程上发现了什么

no-output-to-console-from-a-wpf-application

我可以使用“ Toggle()”功能按预期显示和隐藏控制台。 第一次执行此操作时,设置“ Console.BackgroundColor”和“ Console.ForegroundColor”即可。

再次隐藏并显示后,带有“ Console.WriteLine”的控制台输出正常工作,但是设置颜色不再有效。

我还注意到,每次新的IntPtr函数“ GetConsoleWindow()”都会返回,也许有帮助。

希望您能理解我的问题并能对我有所帮助。

非常感谢, bfrey

[SuppressUnmanagedCodeSecurity]
public static class ConsoleManager
{
    private const string Kernel32DllName = "kernel32.dll";

    [DllImport(Kernel32DllName)]
    private static extern bool AllocConsole();
    [DllImport(Kernel32DllName)]
    private static extern bool AttachConsole();

    [DllImport(Kernel32DllName)]
    private static extern bool FreeConsole();

    [DllImport(Kernel32DllName)]
    public static extern IntPtr GetConsoleWindow();

    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 lType = typeof(Console);

        System.Reflection.FieldInfo lOut = lType.GetField("_out",
            System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);

        System.Reflection.FieldInfo lError = lType.GetField("_error",
            System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);

        System.Reflection.MethodInfo lInitializeStdOutError = lType.GetMethod("InitializeStdOutError",
            System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);

        Debug.Assert(lOut != null);
        Debug.Assert(lError != null);

        Debug.Assert(lInitializeStdOutError != null);

        lOut.SetValue(null, null);
        lError.SetValue(null, null);

        lInitializeStdOutError.Invoke(null, new object[] {true});

    }

    static void SetOutAndErrorNull()
    {
        Console.SetOut(TextWriter.Null);
        Console.SetError(TextWriter.Null);

    }
}

0 个答案:

没有答案