c# - 从 c# winforms 应用程序将输出写入控制台

标签 c# windows winforms console

<分区>

Possible Duplicate:
How do I show console output/window in a forms application?

有没有办法让 c# winforms 程序写入控制台窗口?

最佳答案

这里基本上可以发生两件事。

  1. 控制台输出

Winforms 程序可以将自身附加到创建它的控制台窗口(或附加到不同的控制台窗口,或者如果需要的话,实际上附加到新的控制台窗口)。一旦连接到控制台窗口,Console.WriteLine() 等就会按预期工作。这种方法的一个问题是程序会立即将控制返回到控制台窗口,然后继续写入,因此用户也可以在控制台窗口中键入。我认为您可以使用带有/wait 参数的 start 来处理这个问题。

Start commsnd syntax

  1. 重定向的控制台输出

这是当有人将您程序的输出通过管道传输到其他地方时,例如。

你的应用> file.txt

在这种情况下附加到控制台窗口实际上会忽略管道。要完成这项工作,您可以调用 Console.OpenStandardOutput() 来获取输出应通过管道传输到的流的句柄。这仅在输出通过管道传输时有效,因此如果您想处理这两种情况,您需要打开标准输出并将其写入并附加到控制台窗口。这确实意味着输出被发送到控制台窗口 到管道,但这是我能找到的最佳解决方案。在我用来执行此操作的代码下方。

// This always writes to the parent console window and also to a redirected stdout if there is one.
// It would be better to do the relevant thing (eg write to the redirected file if there is one, otherwise
// write to the console) but it doesn't seem possible.
public class GUIConsoleWriter : IConsoleWriter
{
    [System.Runtime.InteropServices.DllImport("kernel32.dll")]
    private static extern bool AttachConsole(int dwProcessId);

    private const int ATTACH_PARENT_PROCESS = -1;

    StreamWriter _stdOutWriter;
  
    // this must be called early in the program
    public GUIConsoleWriter()
    {
        // this needs to happen before attachconsole.
        // If the output is not redirected we still get a valid stream but it doesn't appear to write anywhere
        // I guess it probably does write somewhere, but nowhere I can find out about
        var stdout = Console.OpenStandardOutput();
        _stdOutWriter = new StreamWriter(stdout);
        _stdOutWriter.AutoFlush = true;

        AttachConsole(ATTACH_PARENT_PROCESS);
    }

    public void WriteLine(string line)
    {
        _stdOutWriter.WriteLine(line);
        Console.WriteLine(line);
    }
}

关于c# - 从 c# winforms 应用程序将输出写入控制台,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14199850/

相关文章:

c# - 通过 C# 代码更改复选框的文本大小

c# - 如何在互联网中断后继续或恢复 FTP 上传

c++ - 有没有办法接收有关在 Windows 中启动的进程的事件?

c# 从 System.Data.DataRowView 转换为字符串

python - Conda未安装PackageNotInstalledError : Package is not installed in prefix

windows - 如何更改 "go build"的构建路径?

c# - 如何在 Visual Studio 中为字体类型使用 DefaultValueAtribute 类?

c# - C#-从类内部调用方法

c# - 如何在没有作业程序集的本地副本的情况下在 Quartz.net 中安排远程作业?

调用回调函数时出现C#异常