Redirect console output to textbox in separate program

前端 未结 5 2055
误落风尘
误落风尘 2020-11-22 16:16

I\'m developing an Windows Forms application that requires me to call a separate program to perform a task. The program is a console application and I need to redirect stan

5条回答
  •  佛祖请我去吃肉
    2020-11-22 16:39

    This works for me:

    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
    }
    

提交回复
热议问题