Windows 窗体中的 Powershell 进度条 [英] Powershell Progress Bar in Windows Forms
问题描述
我正在尝试向 powershell 中的表单添加进度条.我不想使用 PowerShell 的 Write-Progress cmdlet(因为当我从命令行运行脚本时,它会显示一个基于文本的进度条,而我总是想要一个基于表单/图形的进度条).
I'm trying to add a progress bar to a form in powershell. I do not want to use PowerShell's Write-Progress cmdlet (because when I run the script from command line, it shows a text-based progress bar and I always want a form/graphic based bar).
我已经试过了,它似乎有效(在网上找到):
I've tried this and it seems to work(found online):
[reflection.assembly]::loadwithpartialname("System.Windows.Forms") | Out-Null
[reflection.assembly]::loadwithpartialname("System.Drawing") | Out-Null
$form_main = New-Object System.Windows.Forms.Form
$progressBar1 = New-Object System.Windows.Forms.ProgressBar
$timer1 = New-Object System.Windows.Forms.Timer
$timer1_OnTick = {
$progressBar1.PerformStep()
}
$form_main.Text = 'ProgressBar demo'
$progressBar1.DataBindings.DefaultDataSourceUpdateMode = 0
$progressBar1.Step = 1
$progressBar1.Name = 'progressBar1'
$form_main.Controls.Add($progressBar1)
$timer1.Interval = 100
$timer1.add_tick($timer1_OnTick)
$timer1.Start()
$form_main.ShowDialog()| Out-Null
但是,我不希望事件更新进度条(就像上面示例中的 $timer1_OnTic 一样)我想通过在整个脚本中进行调用来自己更新它,例如:
However, I do not want an event to update the progress bar (as does $timer1_OnTic in the example above) I want to update it myself by making calls throughout my script such as:
$progressBar1.PerformStep()
或
$progressBar1.Value = 10
因此,每当我调用 PerformStep() 或更改 progressBar 的值时,我似乎都需要某种后台工作者来更新进度条
So it seems I need some sort of background worker that updates the progress bar whenever I make calls to PerformStep() or change the value of the progressBar
调用 ShowDialog 会停止脚本内的所有处理,直到表单关闭.
Calling ShowDialog stops all processing inside the script until the form is closed.
推荐答案
如果我理解正确,您应该能够将 ShowDialog() 更改为 Show(),这将显示对话框而不会阻止您的脚本.然后您可以继续执行并更新进度条.
If I understand correctly, you should be able to change ShowDialog() to Show(), which will display the Dialog without blocking your script. You can then continue execution and update the progress bar.
您可能会对表单缺乏交互性感到失望.
You may be disappointed in the lack of interactivity of the form though.
这篇关于Windows 窗体中的 Powershell 进度条的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!