winforms 重新获得单击表单中按钮的能力

cuxqih21  于 2023-01-02  发布在  其他
关注(0)|答案(1)|浏览(110)

我正试图得到一个表单来显示脚本的后台进度,并有能力在脚本完成后通过按钮关闭它。文本框刷新后,但我不能按下按钮。请告知。

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}
dced5bon

dced5bon1#

正如注解中所述,与.Show()不同,.Show()只会显示窗体并重新获得对线程的控制权,而您希望调用.ShowDialog().ShowDialog()会阻塞线程并自动刷新窗体。
关于每2秒向TextBox添加一个项目,您可以使用Form's 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()

相关问题