简体   繁体   中英

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. 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.

Regarding adding an item each 2 seconds to your TextBox , you can use the Form's Shown event:

$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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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