In powershell, use
In summary,
function func1{
for($i=0;$i-lt10;$i++){
Write-Host$i
start-sleep1
}
}
$form.Add_Shown({func1})
$form.ShowDialog()
It's like this.
The x button in the upper right corner of the window or Ctrl-C does not work during the for loop process.
What should I do?
The $form
used is probably System.Windows.Forms.Form, so you must first process Windows messages and register with an event handler for the expected event.
X
) button click and take corresponding actionfor
loop, a flag variable for determination is defined and initialized, and setting is performed by the handler.for
loop, the loop is terminated.
about_ScopesYou can do the following.
Add-Type-AssemblyName System.Windows.Forms
$form = New-Object System.Windows.Forms.Form
$script:Cancel=$false####Flag variable for abort/termination determination
#### Closing event handler definition/registration such as closing button
$Close={
$form.Visible=$False
$script:Cancel=$True
}
$form.Add_Closing($Close)
#### KeyDown event handler definition and registration for Ctrl-C key determination
$KDown = {
if($_.KeyCode-eq "C") - And $_.Control)
{
$form.Visible=$False
$script:Cancel=$True
}
}
$form.Add_KeyDown($KDown)
#### Copy from questions and add action
function func1 {
for($i=0;$i-lt10;$i++){
Write-Host$i
System.Windows.Forms.Application::DoEvents()### Window Message Processing
if($script:Cancel) {#### Abort/End Decision and Loop Termination
break
}
start-sleep1
}
}
$form.Add_Shown({func1})
$form.ShowDialog()
$form.Dispose()
© 2024 OneMinuteCode. All rights reserved.