【问题标题】:Show Command Prompt Output with BackgroundWorker.Backgroundworker使用 BackgroundWorker.Backgroundworker 显示命令提示符输出
【发布时间】:2017-06-06 17:31:42
【问题描述】:

我有一个使用异步后台工作程序执行批处理文件的程序。代码如下:

public static void Execute(CmdObj obj, bool batch)
{
    CmdObj = obj;

    var theWorker = new BackgroundWorker();
    theWorker.RunWorkerCompleted += WorkerCompleted;
    theWorker.WorkerReportsProgress = true;

    if(batch)
    {
        theWorker.DoWork += WorkerBatchWork;
    }else{
        theWorker.DoWork += WorkerCommandWork;
    }
    theWorker.RunWorkerAsync();

}

private static void WorkerBatchWork(object sender, DoWorkEventArgs e)
{
    RunBatch(CmdObj);
}

private static void WorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    var temp = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase);
    if (temp != null)
        ProgramPath = temp.Substring(6);

    WriteLog(CmdObj.Activity, false);
    WriteLog(CmdObj.Error, true);

    CmdObj.TheButton.Enabled = true;
}

private static void RunBatch(CmdObj obj)
{
    var process = new Process();
    var startInfo = new ProcessStartInfo
                        {
                            FileName = obj.SrcFile,
                            WindowStyle = ProcessWindowStyle.Normal,
                            CreateNoWindow = false,
                            RedirectStandardInput = true,
                            RedirectStandardOutput = false,
                            RedirectStandardError = true,
                            UseShellExecute = false
                        };


    try
    {
        if (!obj.SrcFile.ToLower().Trim().EndsWith(".bat"))
            throw new FileLoadException("Not a valid .bat file",obj.SrcFile);

        process.StartInfo = startInfo;
        process.Start();
        process.WaitForExit();

        //obj.Activity = process.StandardOutput.ReadToEnd();
        obj.Error = process.StandardError.ReadToEnd();

    }
    catch (Exception ex)
    {
        obj.Exception = ex;
    }
    finally
    {
        process.Close();
    }
}

class CmdObj
{
    public string Command { get; set; }
    public string SrcFile { get; set; }
    public string Activity { get; set; }
    public string Error { get; set; }
    public Exception Exception { get; set; }
    public Button TheButton { get; set; }
}

所以当我运行这个程序并选择一个批处理文件来执行时,我得到一个空白的 CMD 窗口。当我的程序执行批处理文件时,有什么方法可以在 CMD 窗口中显示输出吗?或者,如果我可以将 CMD 输出发送到文本框或其他控件(实时),那也可以。

谢谢!

【问题讨论】:

  • 抱歉,请您描述一下CmdObj 指的是什么? :)
  • 是的,抱歉,更新了上面的代码。它只是我写的一个容器。
  • 我正在添加更多代码,因为上面的 RunBatch 不是直接调用的。这包括 BackgroundWorker 声明。谢谢!
  • 哦,好吧,我还是做到了。也许将来对其他人有用!
  • 问题出在以下行RedirectStandardInput = true,。在您的应用程序中使用它是否重要?我正在尝试找出导致问题的原因

标签: c# cmd


【解决方案1】:

由于您将以下属性之一设置为true,您将获得一个空白的黑色窗口

RedirectStandardInput
RedirectStandardOutput
RedirectStandardError 

这实际上会发生,因为您已经告诉您的应用程序从目标进程接收/发送输出/输入

我看到您正在尝试使用此行从批处理文件中获取输出

//obj.Activity = process.StandardOutput.ReadToEnd();

不幸的是,除非您将RedirectStandardOutput 设置为True,否则这将不起作用,以便您的应用程序能够从目标批处理文件中读取输出。否则输出为空

示例

private void RunBatch(CmdObj obj)
{
    var process = new Process();
    var startInfo = new ProcessStartInfo
    {
        FileName = obj.SrcFile,
        WindowStyle = ProcessWindowStyle.Normal,
        CreateNoWindow = false,
        RedirectStandardInput = true,
        RedirectStandardOutput = true, //This is required if we want to get the output
        RedirectStandardError = true,
        UseShellExecute = false
    };


    try
    {

        if (!obj.SrcFile.ToLower().Trim().EndsWith(".bat"))
        throw new FileLoadException("Not a valid .bat file",obj.SrcFile);

        process.StartInfo = startInfo;
        process.Start();
        process.WaitForExit();

        obj.Activity = process.StandardOutput.ReadToEnd(); //Get the output from the target process
        obj.Error = process.StandardError.ReadToEnd();

    }
    catch (Exception ex)
    {
        obj.Exception = ex;
    }
    finally
    {
        process.Close(); //Terminate the process after getting what is required
    }
}

注意UseShellExecute 必须是False 才能使用RedirectStandardOutput

谢谢,
希望对您有所帮助 :)

【讨论】:

    【解决方案2】:

    你不需要打电话吗

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

    进程开始后? 如果我没记错的话,如果没有这个,我会遇到一些问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-16
      • 1970-01-01
      • 2021-06-30
      • 2014-11-23
      • 1970-01-01
      • 1970-01-01
      • 2017-06-22
      • 1970-01-01
      相关资源
      最近更新 更多