Building a GUI with Windows Forms in Visual Studio

Requires a PowerShell Pro Tools license.

Creating a Project

You can create a module or script project.

Click File->New->Project

Select the Module or Script project type, name it and then click Ok.

Create the Form

After installing the Pro tools, you should now have a Form item template available. Right click on your project and select Add->New Item.

Once the New Item dialog pops up, select the PowerShell Form template, name it and click Ok.

Working with the Form Designer

Adding Controls

The form designer works the same way with any language. You can select items from the Toolbox window and drag them onto your form. Properties of the controls can be set using the Properties window.

Adding controls automatically updates the Form.Designer.ps1 file. Do not edit this file by hand as the editor will simply recreate it after changes are made to the form.

Adding Event Handlers

To do anything interesting, you’ll need to add event handles. You can access a control’s events by selecting it in the designer and clicking the Event button in the Properties window.

Enter the name of your event handler function and click enter.

After you press enter, you will be moved into the code-behind view where you can wire up your event handler.

The event handler will automatically be wired up to your control.

Debugging A Form

Once you are ready to test out your form, you can click Start or press F5 from either the designer window or the code-behind window. PoshTools will fire off the script and you can set breakpoints and debug like any other PowerShell script.

And just like that you have a working Windows Form.

Accessing Controls Added to the Form

In many circumstances, you’ll want to access a control that you’ve add to the form. The $MainForm variable will have parameters for each of it's child items. You can access those through the control's name.

$MainForm.lblMyLabel.Value = "Some Text"

Conclusion

The PowerShell scripts generated by PoshProTools can be used in any PowerShell host. The designer and code-behind files can be joined into a single script. You can use the bundling functionality of PoshProTools to do this automatically.

Last updated