【问题标题】:Console output in winforms GUI applicationwinforms GUI 应用程序中的控制台输出
【发布时间】:2020-04-01 02:47:04
【问题描述】:

全部!

请就我的问题提供任何建议:我构建了 GUI WinForms 应用程序,现在我想将控制台附加到它。我发现这并不像以前那么容易。但我在这里找到了很好的解决方案:How do I show a console output/window in a forms application? 下面的代码来自rag 答案。

using System;
using System.Runtime.InteropServices;

namespace SomeProject
{
    class GuiRedirect
    {
    [DllImport("kernel32.dll", SetLastError = true)]
    private static extern bool AttachConsole(int dwProcessId);
    [DllImport("kernel32.dll", SetLastError = true)]
    private static extern IntPtr GetStdHandle(StandardHandle nStdHandle);
    [DllImport("kernel32.dll", SetLastError = true)]
    private static extern bool SetStdHandle(StandardHandle nStdHandle, IntPtr handle);
    [DllImport("kernel32.dll", SetLastError = true)]
    private static extern FileType GetFileType(IntPtr handle);

    private enum StandardHandle : uint
    {
        Input = unchecked((uint)-10),
        Output = unchecked((uint)-11),
        Error = unchecked((uint)-12)
    }

    private enum FileType : uint
    {
        Unknown = 0x0000,
        Disk = 0x0001,
        Char = 0x0002,
        Pipe = 0x0003
    }

    private static bool IsRedirected(IntPtr handle)
    {
        FileType fileType = GetFileType(handle);

        return (fileType == FileType.Disk) || (fileType == FileType.Pipe);
    }

    public static void Redirect()
    {
        if (IsRedirected(GetStdHandle(StandardHandle.Output)))
        {
            var initialiseOut = Console.Out;
        }

        bool errorRedirected = IsRedirected(GetStdHandle(StandardHandle.Error));
        if (errorRedirected)
        {
            var initialiseError = Console.Error;
        }

        AttachConsole(-1);

        if (!errorRedirected)
            SetStdHandle(StandardHandle.Error, GetStdHandle(StandardHandle.Output));
    }
}

除了一个缺点外,这段代码的作用就像魅力:非拉丁字母以奇怪的编码输出到控制台(但如果重定向到文件,它们是正确的编码)。我需要重定向 StdOut 和 StdErr,如果我更改代码的任何部分,它就会停止重定向。

【问题讨论】:

标签: c# winapi console


【解决方案1】:

感谢所有在 cmets 与我分享智慧的人!

SetConsoleOutputCP 就是答案。

别忘了把它放到类的其他定义中。

[DllImport("kernel32.dll")]
static extern bool SetConsoleOutputCP(uint wCodePageID);

然后添加调用 SetConsoleOutputCP(desired codepage);到 Redirect() 方法。

【讨论】:

    猜你喜欢
    • 2011-03-22
    • 1970-01-01
    • 2019-03-18
    • 1970-01-01
    • 1970-01-01
    • 2015-11-18
    • 1970-01-01
    • 2012-12-21
    • 2014-04-07
    相关资源
    最近更新 更多