Loading…

Building a GUI with Windows Forms in Visual Studio

Applies to:

You will need the following:

  • Visual Studio 2015 and Visual Studio 2017
  • PowerShell Pro Tools for Visual Studio 2015 and 2017

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 main circumstances, you’ll want to access a control that you’ve add to the form. You can use the $MainForm.Controls collection to access your control. For example, if you added $lblMyLabel to your form, you could dynamically change the text by using Where-Object to retrieve the label and then setting the value property of $lblMyLabel.

$lblMyLabel = $MainForm.Controsl | Where-Object "Name" -EQ "lblMyLabel"
$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.