我需要从我的C++/.NET中读取本地C++控制台应用程序的输出。有很多关于这方面的文章,但大多数人一直等到流程结束才读取输出结果,我不想这样做,我需要在流程“结束”之后立即读取它(并且不想要在这样做时阻止GUI,但这是我自己可以做的事情)。我尝试了两种方法。一:从控制台程序读取输出
Diagnostics::Process ^process = gcnew Diagnostics::Process;
process->StartInfo->FileName = pathToExecutable;
process->StartInfo->RedirectStandardOutput = true;
process->StartInfo->UseShellExecute = false;
process->StartInfo->CreateNoWindow = true;
process->StartInfo->Arguments = "some params";
process->EnableRaisingEvents = true;
process->OutputDataReceived += gcnew Diagnostics::DataReceivedEventHandler(GUI::Form1::consoleHandler);
process->Start();
process->BeginOutputReadLine();
而且处理程序:
System::Void GUI::Form1::consoleHandler(System::Object^ sendingProcess, System::Diagnostics::DataReceivedEventArgs^ outLine){
GUI::Form1::contentForConsole += outLine->Data + "\n";
}
但调试器证实了这一过程完成后,才被调用。
在我的第二次尝试我试图创建自定义看螺纹:
Diagnostics::Process ^process = gcnew Diagnostics::Process;
process->StartInfo->FileName = pathToExecutable;
process->StartInfo->RedirectStandardOutput = true;
process->StartInfo->RedirectStandardError = true;
process->StartInfo->UseShellExecute = false;
process->StartInfo->CreateNoWindow = true;
process->StartInfo->Arguments = "some params";
processStatic = process; // static class member
process->Start();
System::Windows::Forms::MethodInvoker^ invoker = gcnew System::Windows::Forms::MethodInvoker(reader);
invoker->BeginInvoke(nullptr, nullptr);
和线程功能,直到进程结束等待上的ReadLine功能:
System::Void GUI::Form1::reader(){
System::String^ str;
while ((str = geogenProcess->StandardOutput->ReadLine()) != nullptr)
{
contentForConsole += str; // timer invoked handler then displays this, but this line is called only once the process is finished
}
}
过程可执行。OUPUTS随着时间跨度从几秒到几分钟(取决于实际任务)的许多文本行。
我也对此感兴趣;我们的店里也有类似的问题,但不在关键位置。 – 2009-10-15 19:41:53