Event Handlers
The main function of a ScriptoForm is to display a Microsoft Windows Forms application which is event-driven and executes code in response to events. Typically, these events are initiated by the user of your ScriptoForm such as clicking a button or typing text into an input field. To respond to these events at run-time, you need to provide Event Handlers to each specific event. In a ScriptoForm, these event handlers are implemented as PowerShell script blocks.
As an example, when a user clicks a Button control, an OnClick event is raised which you can listen for, by associating an event (known as “subscribing”) with its handler name, and perform an action with that handler script block. The action that is performed in response to the event depends on the purpose of your ScriptoForm and how you wish to handle it.
In PowerShell, all event handler subscriptions for Microsoft Windows Forms controls follow the pattern
Add_<EventName>. This method allows you to associate a specific event with a corresponding event handler script block. For example, to handle the “Click” event of a button control, you would use the Add_Click method to subscribe to the event.An event handler is assigned to a control using the following covention:
$ControlName.Add_EventName($ControlName_EventName)
- $ControlName: The name of the control.
Example:$ButtonRun - Add_EventName: The name of the event subscription.
Example:Add_Click - ($ControlName_EventName): The name of the script block used to handle the event.
Example:$ButtonRun_Click
Using the above examples would provide the following:
$ButtonRun.Add_Click($ButtonRun_Click)
Example
Section titled “Example”- In the
$ShowFormMainscript block of the Forms region, assign the name of the script block to be used to handle the specific event type to the control. - In the Handlers region, create a matching script block for the handler.
# Assign the "Click" event handler to the $ButtonRun control with the name $ButtonRun_Click:$ButtonRun.Add_Click($ButtonRun_Click)
# Create the $ButtonRun_Click script block to handle the event and add your custom code as needed:$ButtonRun_Click ={ # Add your custom code here...}The above example shows how to assign the $ButtonRun_Click script block to $ButtonRun and create the associated script block.