使用BackgroundWorker.Backgroundworker显示命令提示输出

时间:2012-10-31 01:50:22

标签: c# cmd

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

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输出发送到文本框或其他控件(实时),那也可以。

谢谢!

2 个答案:

答案 0 :(得分:0)

由于您将以下属性之一设置为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

谢谢, 我希望你觉得这很有帮助:)

答案 1 :(得分:0)

你不需要打电话

 process.BeginErrorReadLine();
 process.BeginOutputReadLine();
过程开始后

? 如果我没记错的话,我就会遇到一些问题。