Closing the Form: What you might expect and what really happens
- Details
- Written by David Corrales
- Last Updated: 14 April 2016
- Created: 19 October 2009
- Hits: 16136
Recently I was contacted by one of our users. He commented that the behavior of a script deviated from what he was expecting. He provided me with the following script block for the Button Click Event so that I could help clear up the confusion:
$handler_button3_Click = { # Check that a logfile was specified. If not close the form. if ($textbox2.text -eq "") { Write-host "No Logfile, closing" $form1.close() } # A logfile was specified Write-Host "I have the logfile" }
As you can see, the user is testing to make sure that the the name of the log file was entered into the textbox. If the value is empty, the script will close the form. This is where the behavior deviates from what the user expects. When the user presses the button with the textbox empty, the script generates the following output:
PowerShell continues to execute the last line despite the fact that the script closed the form in the following line. The user’s perception was that the script block will stop executing after the form was closed, but that is not the case. The reason is that PowerShell is not dependent on the form to execute the script, thus it continues to process the rest of script. To PowerShell the $form1.Close() line is just another command to execute. Since PowerShell does not stop the script when the form is closed, the script block needs to be modified in order prevent the execution of the rest of the script. Below I present two alternatives to prevent this from happening:
Add “return” command after closing the form:
$handler_button3_Click = { # Check that a logfile was specified. If not close the form. if ($textbox2.text -eq "") { Write-host "No Logfile, closing" $form1.close() return #exit the script block } # A logfile was specified Write-Host "I have the logfile" }
An alternative would be to add in an “else” statement:
$handler_button3_Click = { # Check that a logfile was specified. If not close the form. if ($textbox2.text -eq "") { Write-host "No Logfile, closing" $form1.close() } # A logfile was specified else #add else statement { Write-Host "I have the logfile" } }
The corrected script block generates the expected output:
As demonstrated, forms in PowerShell may not behave as expected. Users must keep in mind that PowerShell will continue to execute the remaining lines in a script even after closing the form in a previous line; therefore, users must accommodate accordingly.
Note: You can have a button close the form without creating a Click event by setting the button's DialogResult property to any value other than None.
For licensed customers, use the forum associated with your product in our Product Support Forums for Registered Customers.
For users of trial versions, please post in our Former and Future Customers - Questions forum.