显示在winform进度条中运行脚本进度

时间:2011-07-27 08:20:18

标签: c# winforms vbscript wsh

我有以下代码:

Process scriptProc = new Process();
scriptProc.StartInfo.FileName = @"cscript";
scriptProc.Start();
scriptProc.WaitForExit();
scriptProc.Close();

我想隐藏将在执行上述代码时显示的cscript窗口。有什么方法可以在winform进度条控件中显示上面的脚本进度吗?

感谢。

1 个答案:

答案 0 :(得分:2)

要在不显示新窗口的情况下启动流程,请尝试:

    scriptProc.StartInfo.CreateNoWindow = true;

要显示脚本进度,您需要脚本将其进度文本写入stdout,然后让调用程序读取进度文本并将其显示在用户界面中。像这样:

   using ( var proc = new Process() )
    {
        proc.StartInfo = new ProcessStartInfo( "cscript" );
        proc.StartInfo.CreateNoWindow = true;
        proc.StartInfo.RedirectStandardOutput = true;
        proc.StartInfo.UseShellExecute = false;

        proc.OutputDataReceived += new DataReceivedEventHandler( proc_OutputDataReceived );
        proc.Start();
        proc.BeginOutputReadLine();
        proc.WaitForExit();
        proc.OutputDataReceived -= new DataReceivedEventHandler( proc_OutputDataReceived );

    }

void proc_OutputDataReceived( object sender, DataReceivedEventArgs e )
{
    var line = e.Data;

    if ( !String.IsNullOrEmpty( line ) )
    {
        //TODO: at this point, the variable "line" contains the progress
        // text from your script. So you can do whatever you want with
        // this text, such as displaying it in a label control on your form, or
        // convert the text to an integer that represents a percentage complete
        // and set the progress bar value to that number.

    }
}