如何使用WPF读取和写入命令提示符进程(cmd.exe)

时间:2015-12-08 20:33:48

标签: c# wpf perl

我一直在谷歌和SO看了好几个小时,因为我觉得这个问题肯定有问题,但我找不到合适的答案。
许多最相似的问题询问如何在启动过程时发送A命令或一系列命令。我正在寻求帮助的不同之处在于,一旦我启动它,就能够不断地向进程发送和接收命令。基本上在WPF窗口中嵌套实际的命令提示符。

这就是我一直试图运行这个过程的方式。但我无法弄清楚如何告诉进程等待输入响应。

public void startProcess()
    {
        using (Process process = new Process())
        {
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.RedirectStandardError = true;
            process.StartInfo.RedirectStandardInput = true;
            process.StartInfo.CreateNoWindow = true;
            process.StartInfo.WorkingDirectory = "C:\\";
            process.StartInfo.FileName = @"cmd.exe"; // 

            process.OutputDataReceived += ProcessOutputDataHandler;
            process.ErrorDataReceived += ProcessErrorDataHandler;

            process.Start();
            process.BeginOutputReadLine();
            process.BeginErrorReadLine();

            using (sWriter = process.StandardInput)
            {
                if (sWriter.BaseStream.CanWrite)
                {
                    sWriter.WriteLine(@"cd C:\Users\username\Desktop\SomeFolder\ ");
                    sWriter.WriteLine(@"Run_Script.pl");
                }
            }

            process.WaitForExit();
        }
    }

    private void btnSend_Click(object sender, RoutedEventArgs e)
    {   
       // this method won't work, but this is the general idea I'm trying to figure out to implement.
        if (sWriter.BaseStream.CanWrite)
        {
            sWriter.WriteLine(txtInput.Text);
        }
    }

    public void ProcessOutputDataHandler(object sendingProcess, DataReceivedEventArgs outLine)
    {
        // log is a output textbox that is updated on a timer
        txtLog.Dispatcher.BeginInvoke(new Action(() => { log += outLine.Data; }), null); 

    }

    public void ProcessErrorDataHandler(object sendingProcess, DataReceivedEventArgs outLine)
    {
        txtLog.Dispatcher.BeginInvoke(new Action(() => { log += outLine.Data; }), null); 

    }

我在这上面标记了perl只是因为我试图用这个来运行perl脚本。

0 个答案:

没有答案