PowerShell Studio: OnApplicationLoad Function
- Written by David Corrales
- Last Updated: 21 April 2016
- Created: 06 January 2010
- Hits: 3348
Recently on the forums we had a user who wanted to know why he couldn’t initialize the form controls within the OnApplicationLoad function. Seeing how this can result in some confusion, we would like to elaborate on the subject.
The purpose of OnApplicationLoad is to initialize any dependencies necessary for your form script to run, such as PSSnapins. In the case where the necessary dependencies are unavailable, you can return $false and the form will not display.
To understand why you can’t access the form controls within the OnApplicationLoad function, you need to understand when and where the OnApplicationLoad is called.
The following diagram demonstrates the process flow of the generated script:
As you can see the OnApplicationLoad is called before the GenerateForm function is called. If the OnApplicationLoad returns $true, the script will call the GenerateForm function, which contains the form code including your custom event scripts; therefore the controls only exist in the scope of this function. Once the form is closed, the OnApplicationExit function is called. The OnApplicationExit function can be used to remove any dependencies you may have included. Like the OnApplicationLoad, the form controls are out of scope when the OnApplicationExit is called.
Since the form controls are not accessible by the OnApplicationLoad function where can you dynamically initialize the controls? The answer lies in the Form’s Load event. The Load event will fire the right before the form is displayed, but after the controls are defined, making the event an ideal location for initialization.
To add a Load event handler simply double click on the Form in the Designer or use the Properties Panel’s Events Tab and type in the event handler name next to the Load entry.
Now that you have a Load Event Handler you can use Read-Host or other methods to initialize your controls.
PowerShell Studio includes various sample forms and one of particular interest to this subject is SystemInformation.pff. If you refer to the SystemInformation.pff sample, you will notice that in the OnApplicationLoad is used to prompt the user for the path to a text file that contains a list of computer names. The path is stored in a script scope variable: $script:list. If the file is not found, the OnApplicationLoad returns $false and the form is never displayed.
In the form’s Load event ($PopulateList), the script calls uses the $list variable (initialized in OnApplicationLoad) to load a list of computer names into a ComboBox control. Since the $list variable was declared in the script scope, the Load event is able to access it.
To recap, the OnApplicationLoad function is used to pre-initialize your script, but it can not access the form controls. Instead it is recommended to use the Load event of the form to directly initialize the controls.