我正在开发一个 Windows 窗体应用程序,它需要我调用一个单独的程序来执行任务。该程序是一个控制台应用程序,我需要将标准输出从控制台重定向到程序中的文本框。
我从我的应用程序执行程序没有问题,但我不知道如何将输出重定向到我的应用程序。我需要在程序运行时使用事件捕获输出。
控制台程序并不意味着停止运行,直到我的应用程序停止并且文本以随机间隔不断变化。我试图做的只是挂钩控制台的输出来触发事件处理程序,然后该事件处理程序可用于更新文本框。
我使用 C# 编写程序并使用 .NET 框架进行开发。原始应用程序不是 .NET 程序。
编辑:
这是我想要做的示例代码。在我的最终应用程序中,我将用代码替换 Console.WriteLine 以更新 TextBox。我试图在我的事件处理程序中设置一个断点,但它甚至没有到达。
void Method()
{
var p = new Process();
var path = @"C:\ConsoleApp.exe";
p.StartInfo.FileName = path;
p.StartInfo.UseShellExecute = false;
p.OutputDataReceived += p_OutputDataReceived;
p.Start();
}
static void p_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
Console.WriteLine(">>> {0}", e.Data);
}
这对我有用:
void RunWithRedirect(string cmdPath)
{
var proc = new Process();
proc.StartInfo.FileName = cmdPath;
// set up output redirection
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.RedirectStandardError = true;
proc.EnableRaisingEvents = true;
proc.StartInfo.CreateNoWindow = true;
// see below for output handler
proc.ErrorDataReceived += proc_DataReceived;
proc.OutputDataReceived += proc_DataReceived;
proc.Start();
proc.BeginErrorReadLine();
proc.BeginOutputReadLine();
proc.WaitForExit();
}
void proc_DataReceived(object sender, DataReceivedEventArgs e)
{
// output will be in string e.Data
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)