【问题标题】:Showing running script progress in winform progressbar在 winform 进度条中显示正在运行的脚本进度
【发布时间】:2023-07-05 18:21:02
【问题描述】:

我有以下代码:

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

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

谢谢。

【问题讨论】:

  • 你能附加一个监听器,它在每次 cscript 写入控制台时运行?如果是这样,您可以通过解析输出来监控进度,从而更新进度条。
  • 任何带有完整源代码示例的最终解决方案?

标签: c# winforms vbscript wsh


【解决方案1】:

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

    scriptProc.StartInfo.CreateNoWindow = true;

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

   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.

    }
}

【讨论】:

  • 谢谢。您的回答使我找到了解决问题的方法。