The powerhell GUI fails to exit during sleep.

Asked 1 years ago, Updated 1 years ago, 397 views

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?

powershell

2023-01-14 22:47

1 Answers

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.

  • Add DoEvents() to the loop because the loop only between Write and Sleep does not process Window messages. (However, there are articles such as Why shouldn't you use the Application.DoEvents method, so you can look for other ways.)
  • Define and register the handler for KeyDown event to detect Ctrl+C and perform the abort/termination process in the handler.
  • Define and register handlers for Closing event to detect a close (X) button click and take corresponding action
  • As there is no determination or means for terminating the
  • for loop, a flag variable for determination is defined and initialized, and setting is performed by the handler.
    If the flag is set in the for loop, the loop is terminated. about_Scopes

You 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()


2023-01-15 02:08

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.