I created this simple example form to show my problem.
Once you press the start button, the TestFunction function starts and will execute 50 pings that will be reported in the $ outbox below.
My problem is to stop the function, I would like to set a button to terminate the function WITHOUT exiting the form.
Unfortunately when the ping function is running I can't click on any button, only when it has finished.
Thank you in advance
Code: Select all
cls
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
$Form = New-Object System.Windows.Forms.Form
$Form.Size = New-Object System.Drawing.Size(600,400)
$Form.StartPosition = "CenterScreen"
Function TestFunction {
$Ping = @()
$count = 50
While ($Count -gt 0){
$ping = Get-WmiObject Win32_PingStatus -Filter "Address = '8.8.8.8'" |
select @{Label="TimeStamp";Expression={Get-Date}},
@{Label="Source";Expression={ $_.__Server }},
@{Label="Destination";Expression={ $_.Address }},
IPv4Address
Write-Verbose ($ping | out-string)
$count --
Start-Sleep -Seconds 1
$i = $Count
foreach ($item in $Count){
$text = $Ping.Source, $Ping.Destination, $Ping.IPv4Address, $Ping.Bytes, $Ping."Time(ms)" -join ' '
$outputBox.AppendText("$text `r`n")
$i++
}
}
}
$Button = New-Object System.Windows.Forms.Button
$Button.Location = New-Object System.Drawing.Size(20,30)
$Button.Size = New-Object System.Drawing.Size(110,80)
$Button.Text = "START"
$Button.BackColor = "LightGreen"
$Button.Cursor = [System.Windows.Forms.Cursors]::Hand
$Button.Font = New-Object System.Drawing.Font("Calibri",11,[System.drawing.FontStyle]::Bold)
$Button.Add_Click({TestFunction})
$Form.Controls.Add($Button)
$outputBox = New-Object System.Windows.Forms.TextBox
$outputBox.Location = New-Object System.Drawing.Size(10,180)
$outputBox.Size = New-Object System.Drawing.Size(565,50)
$outputBox.MultiLine = $True
$outputBox.SelectionStart = $outputBox.Text.Length;
$outputBox.ScrollToCaret() = $true
$outputBox.ScrollBars = "Vertical"
$Form.Controls.Add($outputBox)
$Form.Add_Shown({$Form.Activate()})
[void] $Form.ShowDialog()