简体   繁体   English

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

[英]Regain ability to click button in form

I'm trying to get a form to show a background progress of the script and have the ability to close it via button after the script completes.我正在尝试获取一个表格来显示脚本的后台进度,并能够在脚本完成后通过按钮关闭它。 The TextBox refreshes as supposed but I cannot click the button after. TextBox 按预期刷新,但之后我无法单击按钮。 Please advise.请指教。

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}

 

As stated in comments, instead of .Show() which will simply display your form and regain control of your thread you want to call .ShowDialog() instead which blocks the threads and refreshes the form automatically.正如评论中所述,而不是.Show()它只会显示您的表单并重新获得您想要调用的线程的控制权.ShowDialog()而不是阻塞线程并自动刷新表单。

Regarding adding an item each 2 seconds to your TextBox , you can use the Form's Shown event:关于每 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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM