Winform跑马灯进度条冻结

Winform marquee progress bar freezes

我写了一个小脚本作为跑马灯进度条的测试。问题是进度条冻结。此外,保存在 $files 变量中的文件列表不会在最后显示,而是在脚本完成后调用时显示内容。任何见解都会有所帮助。

Add-Type -AssemblyName System.Windows.Forms

[System.Windows.Forms.Application]::EnableVisualStyles()
$path = "C:\"

$window = New-Object Windows.Forms.Form
$window.Size = New-Object Drawing.Size @(400,200)
$window.StartPosition = "CenterScreen"
$window.Font = New-Object System.Drawing.Font("Calibri",11,[System.Drawing.FontStyle]::Bold)
$window.Text = "STARTING UP"

$ProgressBar1 = New-Object System.Windows.Forms.ProgressBar
$ProgressBar1.Location = New-Object System.Drawing.Point(10, 10)
$ProgressBar1.Size = New-Object System.Drawing.Size(365, 20)
$ProgressBar1.Style = "Marquee"
$ProgressBar1.MarqueeAnimationSpeed = 20
$ProgressBar1.UseWaitCursor = $true
$ProgressBar1.Visible = $false

$button = New-Object System.Windows.Forms.Button
$button.size = New-Object drawing.size @(50,50)
$button.Location = New-Object System.Drawing.Point(20, 70)
$button.Text = "TEST"
$window.Controls.add($button)

$button.add_Click(
{write-host "ASD"
$ProgressBar1.show()
start-job -name test -ScriptBlock  {gci -File -Recurse "D:\" -ErrorAction SilentlyContinue|select Name}
Wait-job -Name test
$files = Receive-Job -Name test
$ProgressBar1.Hide()
Write-host "$files"
}
)


$window.Controls.Add($ProgressBar1)

$window.ShowDialog()

如我的评论所述,使用 Wait-Job 将阻塞您当前的线程,因此表单也将变得无响应。相反,您可以使用循环 whiledo 来等待您的工作并调用 Application.DoEvents Method 作为解决方法:

$button.Add_Click({
    $ProgressBar1.Show()
    $this.Enabled = $false
    $job = Start-Job -ScriptBlock  {
        Get-ChildItem -File -Recurse $HOME -ErrorAction SilentlyContinue
    }
    while($job.State -eq 'Running') {
        [System.Windows.Forms.Application]::DoEvents()
    }
    $job | Receive-Job -AutoRemoveJob -Wait | Out-Host
    $ProgressBar1.Hide()
    $this.Enabled = $true
})