C# 有没有办法在编写控制台应用程序时创建第二个控制台以在 .NET 中输出?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/697227/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 13:52:42  来源:igfitidea点击:

Is there a way to create a second console to output to in .NET when writing a console application?

c#.netconsole

提问by Matze

Is there a way to create a second console to output to in .NET when writing a console application?

有没有办法在编写控制台应用程序时创建第二个控制台以在 .NET 中输出?

采纳答案by alexn

Well, you could start a new cmd.exe process and use stdio and stdout to send and recieve data.

好吧,您可以启动一个新的 cmd.exe 进程并使用 stdio 和 stdout 来发送和接收数据。

ProcessStartInfo psi = new ProcessStartInfo("cmd.exe")
{
    RedirectStandardError = true,
    RedirectStandardInput = true,
    RedirectStandardOutput = true,
    UseShellExecute = false
};

Process p = Process.Start(psi);

StreamWriter sw = p.StandardInput;
StreamReader sr = p.StandardOutput;

sw.WriteLine("Hello world!");
sr.Close();

More info on MSDN.

有关MSDN 的更多信息。

回答by ólafur Waage

A single console is attached to any given process. So in short you can not. But there are ways to "fake it"

单个控制台附加到任何给定进程。所以总之你不能。但有办法“伪造”

回答by Matrim

The following fires off an application-dependent number of console windows and stores the amount and parameters for the console inside a String Dictionary that is then looped to generate the required amount of spawned console apps. You would only need the process stuff if only spawning one of course.

下面的代码会触发依赖于应用程序的控制台窗口数量,并将控制台的数量和参数存储在一个字符串字典中,然后循环生成所需数量的生成的控制台应用程序。如果只产生一个当然,你只需要进程的东西。

//Start looping dic recs and firing console
foreach (DictionaryEntry tests in steps)
{
    try
    {
        Process runCmd = new Process();
        runCmd.StartInfo.FileName = CONSOLE_NAME;
        runCmd.StartInfo.UseShellExecute = true;
        runCmd.StartInfo.RedirectStandardOutput = false;
        runCmd.StartInfo.Arguments = tests.Value.ToString();

        if (cbShowConsole.Checked)
        {
            runCmd.StartInfo.CreateNoWindow = true;
            runCmd.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
        }
        else
        {
            runCmd.StartInfo.CreateNoWindow = false;
            runCmd.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; 
        }
        runCmd.Start();                
    }
    catch (Exception ex)
    {
        string t1 = ex.Message;
    }
}

Note this is intended either to run hidden (CreateNoWindow) or visible.

请注意,这旨在运行隐藏 (CreateNoWindow) 或可见。