C# - 写入新的控制台窗口

时间:2017-02-13 19:17:49

标签: c# .net

要为我的应用程序编写某种调试扩展,我尝试创建一些可以创建新控制台窗口并向其写入信息的东西。

我写了一个非常简单的ConsoleApplication,它基本上读取它接收的输入,直到它等于terminate

private static void Main(string[] args)
{
    string text;
    while ((text = Console.ReadLine()) != "terminate")
    {
        Console.WriteLine(text);
    }
}

我将此ConsoleApplication添加到我的资源中,然后将其写入新项目中:

// Create the temporary file
string path = Path.Combine(Path.GetTempPath(), "debugprovider.exe");
File.WriteAllBytes(path, Properties.Resources.debugprovider);

// Execute the file
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.UseShellExecute = false;
startInfo.RedirectStandardInput = true;
startInfo.FileName = path;

Process process = new Process();
process.StartInfo = startInfo;
process.Start();

process.StandardInput.WriteLine("Write a new line ...");
process.StandardInput.WriteLine("terminate");
process.WaitForExit();

当我的应用程序关闭时,我也会调用它来删除该文件:

// Delete the temporary file as it is no longer needed
File.Delete(path);

我的问题是我没有看到窗口中的输入,只有一个空白的控制台窗口。我该如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

如果您想要子进程的输出,那么您可能希望将标准输出重定向到并侦听进程的OutputDataReceived事件:

process.RedirectStandardOutput = true;
process.OutputDataReceived += process_OutputDataReceived;

然后在process_OutputDataReceived中处理子进程的输出:

void process_OutputDataReceived(object sender, DataReceivedEventArgs e) {
    Console.Write(e.Data);
}

答案 1 :(得分:0)

试试这个:

var path = Path.Combine(Path.GetTempPath(), "debugprovider.exe");
File.WriteAllBytes(path, Properties.Resources.debugprovider);
using (var cmd = new Process())
{
    cmd.StartInfo = new ProcessStartInfo(path)
    {
        WindowStyle = ProcessWindowStyle.Hidden,
        UseShellExecute = false,
        RedirectStandardInput = true,
        RedirectStandardOutput = true,
        RedirectStandardError = true,
        CreateNoWindow = true
    };
    var outputStringBuilder = new StringBuilder();
    cmd.OutputDataReceived += (sender, e) =>
    {
        if (!String.IsNullOrEmpty(e.Data))
        {
            Console.WriteLine(e.Data);
        }
    };
    var errorStringBuilder = new StringBuilder();
    cmd.ErrorDataReceived += (sender, e) =>
    {
        if (!String.IsNullOrEmpty(e.Data))
        {
            Console.WriteLine(e.Data);
        }
    };
    cmd.Start();
    cmd.StandardInput.WriteLine("Write a new line ...");
    cmd.StandardInput.WriteLine("terminate");
    cmd.StandardInput.Flush();
    cmd.StandardInput.Close();
    cmd.BeginOutputReadLine();
    cmd.BeginErrorReadLine();
    cmd.WaitForExit();
}