0

Please see below code .

[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing") 
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") 

$objForm = New-Object System.Windows.Forms.Form 
$objForm.Text = "Data Entry Form"
$objForm.Size = New-Object System.Drawing.Size(300,200) 
$objForm.StartPosition = "CenterScreen"

$objForm.KeyPreview = $True
$objForm.Add_KeyDown({if ($_.KeyCode -eq "Enter") 
    {$x=$objTextBox.Text;$objForm.Close()}})
$objForm.Add_KeyDown({if ($_.KeyCode -eq "Escape") 
    {$objForm.Close()}})

$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Location = New-Object System.Drawing.Size(75,120)
$OKButton.Size = New-Object System.Drawing.Size(75,23)
$OKButton.Text = "OK"
$OKButton.Add_Click({$i=0; while($i -lt 10){write-host $i;start-sleep 2;$i++} })
$objForm.Controls.Add($OKButton)

$CancelButton = New-Object System.Windows.Forms.Button
$CancelButton.Location = New-Object System.Drawing.Size(150,120)
$CancelButton.Size = New-Object System.Drawing.Size(75,23)
$CancelButton.Text = "Cancel"
$CancelButton.Add_Click({$objForm.Close()})
$objForm.Controls.Add($CancelButton)

$objForm.Topmost = $True

$objForm.Add_Shown({$objForm.Activate()})
[void] $objForm.ShowDialog()

In above code, I want a form listen to cancel button click when while loop is in progress after clicking ok button. I searched heaven but could not find a solution to this problem. In other words, when ok button is clicked, powershell start executing while loop and freezes the control. But I want to override this control and be allowed to click cancel button before while loop is over. Is it possible? Is there any alternative? note: I am using powershell 3.0

Sumedh
  • 1
  • Could you start your "Ok" command as a job and then use `Stop-Job` on "Cancel"? – BenH Mar 27 '17 at 17:30
  • @BenH This is not as easy as it sounds. `Start-Job` would run that code asynchronously, but wouldn't write to the host immediately. – Clijsters Mar 27 '17 at 17:47
  • ...But `Start-Job` would work on the form itself like described [here](http://stackoverflow.com/a/5986829/4068240). [Using events](http://stackoverflow.com/a/20337008/4068240) could then do the trick. – Clijsters Mar 27 '17 at 17:48

0 Answers0