CreateProcess and CreatePipe to execute a process and return output as a string in VC++

前端 未结 2 1562
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-30 17:19

I am trying to use CreateProcess and CreatePipe to execute a process from within a Windows Forms C++/CLR application in Visual Studio 2010.

2条回答
  •  囚心锁ツ
    2020-12-30 17:25

    Thanks to Hans Passant for the lead that got me to this clear and simple piece of code that does exactly what I was looking for.

    /// this namespace call is necessary for the rest of the code to work
    using namespace System::Diagnostics;
    using namespace System::Text;/// added for encoding
    
    Process^ myprocess = gcnew Process;
    Encoding^ Encoding;/// added for encoding
    Encoding->GetEncoding(GetOEMCP());/// added for encoding
    
    myprocess->StartInfo->FileName = "ping.exe";
    myprocess->StartInfo->Arguments = "127.0.0.1";
    myprocess->StartInfo->UseShellExecute = false;
    
    /// added the next line to keep a new window from opening
    myprocess->StartInfo->CreateNoWindow = true;
    
    myprocess->StartInfo->RedirectStandardOutput = true;
    myprocess->StartInfo->StandardOutputEncoding = Encoding;/// added for encoding
    myprocess->Start();
    
    String^ output = gcnew String( myprocess->StandardOutput->ReadToEnd() );
    
    myprocess->WaitForExit();
    
    /// OutputBox is the name of a Windows Forms text box in my app.
    OutputBox->Text = output;
    

    EDIT: Added encoding information. See above code.

提交回复
热议问题