exit from powershell script causes Unhandled excep

2019-08-19 18:30发布

问题:

I am trying to execute exit after closing the form when clicking "NO" button, but exit causes a system error

Code:

    function No {
            $Form.close()
            exit
    }
$NoButton.Add_Click({No}) 

Without exit, it closes the form but it continues executing the script

System error:

Unhandled exception has occured in a component in your application. If you click Continue, the application will ignore this error and attempt to continue.

System error.

Full button code:

function No {
    $Form.close()
    exit
                    } #end No
# No button
$NoButton = New-Object System.Windows.Forms.Button 
$NoButton.Location = New-Object System.Drawing.Size(95,80) 
$NoButton.Size = New-Object System.Drawing.Size(80,20) 
$NoButton.Text = "No" 
$NoButton.Add_Click({No}) 
$NoButton.Cursor = [System.Windows.Forms.Cursors]::Hand
$Form.Controls.Add($NoButton) 

回答1:

You need to wait till the $Form is actually closed and then better kill it's own process:

$NoButton = New-Object System.Windows.Forms.Button 
$NoButton.Location = New-Object System.Drawing.Size(95,80) 
$NoButton.Size = New-Object System.Drawing.Size(80,20) 
$NoButton.Text = "No" 
$NoButton.Add_Click({$Form.close()}) 
$NoButton.Cursor = [System.Windows.Forms.Cursors]::Hand
$Form.Controls.Add($NoButton)
$Form.Add_Closed({Stop-Process -ID $PID})    # Kill it's own process when the form is closed