Page 1 of 1

Stop Function without exit form

Posted: Wed Apr 17, 2019 3:00 am
by ramses147
Hi guys !
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()

Re: Stop Function without exit form

Posted: Wed Apr 17, 2019 5:25 am
by mxtrinidad
Correction:
Check this example.

$count = 10; $i = 1;
While ($i -le $count)
{
Write-Host "Print $i";
$i++
}

Hope this helps!

:)

Re: Stop Function without exit form

Posted: Wed Apr 17, 2019 7:47 am
by davidc
This article may be of assistance to you:

https://info.sapien.com/index.php/guis/ ... sive-loops

As well as this one:

https://info.sapien.com/index.php/guis/ ... sive-forms

If you want to use ping.exe as an alternative, you can use the redirect process output template:

https://www.sapien.com/blog/2018/10/09/ ... -v5-5-155/