Quantcast
Channel: Windows PowerShell forum
Viewing all articles
Browse latest Browse all 21975

How to stop an infinite loop in a GUI, which is running without a console, through a keystroke

$
0
0

Hi All,

This is my first participation in this forum so I hope I'll make it right :-)

I have a PS script running in a GUI application which is started through a shortcut "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -windowstyle hidden" in order to hide the console window. I have extracted the code, this is just a small fragment, that I have problem with as shown below. The purpose is to do a continuos Ping and stop it with a keystroke. The problem is that without any console window the application doesn't get the keystroke. Is there any way to solve this?

# Load library for GUI
add-type -AssemblyName system.windows.forms
add-type -AssemblyName system.drawing

function btnPing_OnClick([string]$computer)
{

    $lblRes.text = "Continuos Ping engaged.`n`nPress any key to stop.`n`n`n"

    while($true)
    {
        $lblRes.text += (ping -n 1 $computer)[2]  | Out-String
        sleep -Seconds 1

        if($Host.UI.RawUI.KeyAvailable -or [console]::KeyAvailable) 
        {
            break;
        }
    }

    $lblRes.text = "`n`n`nPing stopped"
}

# Create a form
$form = New-Object System.Windows.Forms.Form
$form.Size = New-Object System.Drawing.Size(600, 600)

# OutPut Box - Results
$lblRes = New-Object System.Windows.Forms.Richtextbox
$lblRes.Size = New-Object System.Drawing.Size(($form.width - 150),($form.height - 70))
$lblRes.Location = New-Object System.Drawing.Point(130, 22)
$lblRes.Name = "lblRes"
$lblRes.Multiline = $true
$form.Controls.Add($lblRes)

# Textbox - Computer Name
$txtPcName = New-Object System.Windows.Forms.TextBox
$txtPcName.Size = New-Object System.Drawing.Size(110, 20)
$txtPcName.Location = New-Object System.Drawing.Point(7, 21)
$txtPcName.Name = "txtPcName"
$form.Controls.Add($txtPcName)

# Button - Ping
$btnPing = New-Object System.Windows.Forms.Button
$btnPing.Name = "btnPing"
$btnPing.Size = New-Object System.Drawing.Size(110, 20)
$btnPing.Location = New-Object System.Drawing.Point(7, 50)
$btnPing.Text = "Ping"
$btnPing.add_Click({btnPing_OnClick $txtPcName.text})
$form.Controls.Add($btnPing)

# Show form
[void]$form.ShowDialog()


Viewing all articles
Browse latest Browse all 21975


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>