Using Form-Based Windows in PowerShell

by Jul 5, 2016

WPF-based windows are the preferred way to create user interfaces this way – because the code is much easier to write, shorter, and WPF scales well on high-density high-resolution displays.

Still, if you must use Windows Forms, here is a sample to get you started:

Add-Type -AssemblyName System.Windows.Forms
$Form = New-Object system.Windows.Forms.Form
$Form.Text = 'Get Out!'
$Label = New-Object System.Windows.Forms.Label
$Label.Text = 'Fire Alarm!'
$Label.Font = 'Stencil'
$Label.ForeColor = 'Red'
$Label.AutoSize = $True
$Form.Controls.Add($Label)
$Form.ShowDialog()

As you can see, all UI elements need to be created by code, and positioned using pixels. Creating complex UIs is a monster task, and you won't be able to do this without specialized tools that help you.

In the previous tip we illustrated how much easier this is with WPF – and better-looking, too:

Add-Type -AssemblyName PresentationFramework
  

$xaml = @'
<Window
   xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   xmlns_x="http://schemas.microsoft.com/winfx/2006/xaml"
   SizeToContent="WidthAndHeight"
   Title="Get Out!"
   Topmost="True">
      <TextBlock
         Margin="50"
         HorizontalAlignment="Center"
         VerticalAlignment="Center"
         FontFamily="Stencil"
         FontSize="80"
         FontWeight="Bold"
         Foreground="Red">
         Fire Alarm!
      </TextBlock>
</Window>
'@

$reader = [System.XML.XMLReader]::Create([System.IO.StringReader]$XAML)
$window = [System.Windows.Markup.XAMLReader]::Load($reader)
  
$null = $window.Dispatcher.InvokeAsync{$window.ShowDialog()}.Wait()

Twitter This Tip! ReTweet this Tip!