Safely Opening WPF Windows

by Jul 4, 2016

In the previous tip we explained how you can create WPF-based windows in PowerShell. However, when you play with WPF code inside PowerShell ISE, it might occasionally crash, or report "missing quotas" exceptions, indicating a resource problem.

A safe way of opening WPF windows in PowerShell ISE is to not call ShowDialog() directly but instead run the method in the WPF dispatcher context:

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!