PowerShell Studio has a selection of Windows Form templates that you can use to speed up your development. You will most likely be using your own code snippets to add behind the form controls, as well as the snippets available in PowerShell Studio, and perhaps snippets from someone else. This is fine until you start trying to copy/paste an actual event code block.
Basic Button Control
There are many controls we can add to our Windows Form. The Button Control is the one you’ll click that will run your code behind the control and is the most used control in any Windows Forms application.
The image below shows some other controls added to a form:
In the following example I am adding the “Message Box (Yes / No)” code from the PowerShell Studio snippet collection into the “Button1” control. Simply double-click on the snippet and the code will be automatically added to the control:
The result of adding the code inside the Button control is that when the form is executed, pressing “Button1” will execute the code behind the control. But, what’s really happening when you add any control to the form?
Control Event Handler Registration
Here’s where it gets interesting! Every time you drag/drop to add a control—the event handler for that control gets registered in the form. This is important and it’s done behind the scene. What will happened if you decide to delete the code block for the control?
In our example we remove the code block for the “Button1” control:
Removing the code doesn’t remove the “Button1” object from the GUI form:
The following pop-up message will display when you manually remove the control code block:
This indicates that removing the control code will unregister the Control Event Handler for that control in the form. And, once it is removed, copy/pasting the code back won’t work:
The good news—it’s easy to recover Control Event Handlers in PowerShell Studio!
Recovering Control Event Handlers
In order to register back the Control Event Handler:
- In the form Designer, select the control to re-register.
- In the Properties Panel, select the Events lightening-bolt button .
- In the Action section, select the Click event, followed by the control that was added back: “button1_Click“.
After this is done, the “Button1” control will start working when executing the form.
It’s easy to remove and add code back in a Windows Form. Just remember that when it involves Control Event Handlers, you will need to take some extra steps to recover the event. I hope this information will be helpful when working with new and existing forms.
As always, if you have any ideas, comments, or feedback, please visit our feedback forum and reference this post.
Max Trinidad is a Technology Evangelist at SAPIEN Technologies Inc., and a Microsoft PowerShell MVP. You can reach him at email@example.com