Basics: What is an event and how do I handle them?

PowerShell is an object-oriented language built on .NET; object-oriented meaning everything is treated as an object and these objects can easily be extended or modified. An object is simply the programmatic representation of anything. Objects are usually considered as two types of things: Properties, which describe attributes of whatever the .NET object is representing, and Methods, which describe the types of actions that the .NET object can undertake.

But what is an event?

An event is a special kind of method that occurs or is raised when something happens to an object, like when you click a button, resize a window, or load a form. It can also be related to some other program logic, such as changing a property’s value or the result of data that has finished being collected. When the event is raised, the associated event handler is called. Event handlers define what is to happen when an event is triggered.

For PowerShell WinForms, event handlers are added to controls using methods with the following syntax:
add_<EventName> (<Scriptblock>)

Where <EventName> is the name of the event to be handled and <Scriptblock> is the code to be executed when the event is triggered. 

For example, when you have a button in a Window Form and you want to know when that button is clicked, there is an event for that!

Let’s look at the following script:

$form = New-Object Windows.Forms.Form
$button = New-Object Windows.Forms.Button
 
$button_Click={
 $form.Close()
} 
 
$button.Text="Click me!"
$button.add_Click($button_Click)
 
$form.Controls.Add($button)
$form.ShowDialog()

This code creates a button that will close its containing form when it is clicked. The line, $button.add_Click($button_Click), is where the event handler is attached to the control, passing the scriptblock $button_Click.  

In PowerShell Studio’s WinForm Designer, the control event code is generated for you, but it is still important to understand what is happening. If you export (Deploy->Export) a psf file, you can see the generated code.

Summary

Events enable the ability to execute code when a change or action occurs to the event. To respond to an event, an event handler must be defined.

Feedback

As always, any feedback is appreciated. If you have a particular type of blog article or product feature request you would like to see, please submit your suggestions on the Wish List and Feature Requests forum or the new Feature Requests page.