我试图得到一个表单来显示脚本的背景进度,并有能力通过按钮关闭它后脚本完成。文本框按预期刷新,但我不能点击按钮后。请建议。
Add-Type -AssemblyName System.Windows.Forms
Function ButtonClick
{
$mainForm.Close()
}
[System.Windows.Forms.Application]::EnableVisualStyles()
$button = New-Object 'System.Windows.Forms.Button'
$button.Location = '10, 10'
$button.Name = "buttonGo"
$button.Size = '75, 25'
$button.TabIndex = 0
$button.Text = "&Go"
$button.UseVisualStyleBackColor = $true
$button.Add_Click({ButtonClick})
$textBoxDisplay = New-Object 'System.Windows.Forms.TextBox'
$textBoxDisplay.Location = '12, 50'
$textBoxDisplay.Multiline = $true
$textBoxDisplay.Name = "textBoxDisplay"
$textBoxDisplay.Size = '470, 150'
$textBoxDisplay.TabIndex = 1
$mainForm = New-Object 'System.Windows.Forms.Form'
$mainForm.Size = '500, 250'
$mainForm.Controls.Add($button)
$mainForm.Controls.Add($textBoxDisplay)
$mainForm.FormBorderStyle = [System.Windows.Forms.FormBorderStyle]::FixedDialog
$mainForm.Name = "mainForm"
$mainForm.Text = "Show Get-NetConnectionProfile Output"
cls
$mainForm.Show()
$1 = @([pscustomobject]@{name = 'Time'},
[pscustomobject]@{name = 'Zenek'},
[pscustomobject]@{name = 'NetEx'},
[pscustomobject]@{name = 'Busy'},
[pscustomobject]@{name = 'Shorts'})
$1|%{$textBoxDisplay.Text += "$($_.name) already present`r`n"; $textBoxDisplay.Refresh(); Start-Sleep -s 2}
如注释中所述,.Show()
将简单地显示您的表单并重新控制您的线程,而不是调用.ShowDialog()
,它会阻塞线程并自动刷新表单。
关于每2秒添加一个项目到你的TextBox
,你可以使用表单的Shown
事件:
$mainForm.Add_Shown({
@(
[pscustomobject]@{name = 'Time'}
[pscustomobject]@{name = 'Zenek'}
[pscustomobject]@{name = 'NetEx'}
[pscustomobject]@{name = 'Busy'}
[pscustomobject]@{name = 'Shorts'}
) | ForEach-Object {
$textBoxDisplay.Text += "$($_.name) already present`r`n"
Start-Sleep 2
}
})
$mainForm.ShowDialog()