I’ve finally given over trying to improve PowerBoots for this iteration of development, and in between setting up the ScriptingGames.PoshCode site and releasing the PoshCode software on the main PoshCode.org site (it’s coming, I promise), I decided to take a few minutes and release this lates PowerBoots, and it’s a ground-breaking release, if I do say so myself!
There are three huge changes in this release, actually. But the biggest one is that most of the functionality works in the released version of PowerShell 1.0! There are still a few glitches and bugs when it’s running in 1.0, but I’ve decided it’s past time I just release it and let you start using it! If you use it on 1.0, please let me know if you run into anything weird, or problems you can’t figure out workarounds for.
The second biggest change is that all of the functions are now cached. The first time it’s loaded, PowerBoots actually writes out a few hundred scripts files into a “Functions” subfolder, and from then on, they’re only loaded when they’re used — saving you a lot of time at startup, and a lot of memory. Additionally, when you load in additional controls, such as the Visifire WPF chart controls, those functions are cached permanently too, so you never even have to manually load the assembly again!
A few people have asked over the last few months about how to set attached properties and dependency properties in WPF from PowerShell, so in this release I’ve included full support for these in a way that will, I hope, simply work so well it will boggle your mind
All you have to do to tell a control, for instance, to be in the 3rd column of a grid is to just pass Button "Click Me" -"Grid:Column" 2 … it’s THAT simple. In fact, for properties that have unique names, you don’t even have to specify the type, just the name, like -Row 3 to specify the grid row.
Of course, the downside of these changes is that some of the syntax has changed a little bit. All scripts and event handlers (ie: click handlers for WPF Buttons) are run from the dll module scope in PowerShell 2 (the global scope in PowerShell 1), which means that they can’t access “script” scope variables from your scripts (which ends up meaning you have to declare a lot of things global that you could leave in script scope before). Just to be clear on the quality of this release: once we have ironed out the minor problems we’re having with PowerShell 1.0 in a way that I’m comfortable with, I expect to push the version number up and release an 1.0 Release Candidate, barring any major issues.
In order to help with the transition, I’ve included a Samples.ps1 script which has 28 sample scripts in it (mostly from the original Tutorial Walk-through, which I will update soon). I’ve updated each of them to work with this release, in both PowerShell 1 and PowerShell 2 (which means they’re almost all written in PowerShell 1 syntax), so you can use them as good examples of how to get things done!
Please use the Discussions Forum and Issue Tracker on the CodePlex site to post any problems you have, and I’ll try to write up a few more posts describing changes and differences in the next couple of weeks.
Please excuse me if I start by just copying the basic ideas of the Shoes Tutorial, but I figured that since PowerBoots is inspired by Shoes, that was as good a place as any to start. PowerBoots (or just “Boots”) is a PowerShell 2.0 module with functions for writing Windows Presentation Framework (WPF) applications in the PowerShell scripting language. You should get the latest version of PowerBoots before continuing, and install it by putting the “PowerBoots” folder in one of your “Modules” folders (list them by typing $Env:PSMODULEPATH in PowerShell v2).
Don’t forget to start PowerShell.exe with the STA parameter (This is no longer required in PowerBoots 0.1).
Did I hear someone ask what is WPF? It was introduced as part of .Net 3.0 (and vastly improved in .Net 3.5), so you can expect to find it preinstalled on computers from Vista on, and of course you can download and install it on XP if it’s not already installed. The only thing you really need to know about WPF for the purposes of this tutorial is that it is the new GUI toolkit for .Net, and that it is container based — you put elements into other elements to control the layout, rather like HTML and Java Swing… you can pick up the rest as we go along.

The parenthesis ( and ) are a container, so the button is “in” the Window. You can also pass a ScriptBlock instead, which works basically the same way. Of course, this is a bit uglier than the Shoes syntax, so lets see if we can’t clean it up some. The -Content parameter is positional, so the first non-named argument you pass will be used for that. The same is true for the -Children parameter of panels, and in fact, each of the other similar parameters: Items, Blocks, and Inlines.
We have used a function New-BootsWindow which has an alias Boots. Boots takes all the same parameters as the Window function mentioned previously, but it uses slightly more useful defaults, and has a few other major benefits as well, the first of which is that it automatically “shows” the window, and the second is that it supports an -Async parameter which allows the window to come out in a new thread so that you can continue using PowerShell while the window remains alive and responsive. There is one catch: New-BootsWindow cannot take it’s content on the pipeline (the old function, now renamed “Out-BootsWindow” can take pipeline content, but is a script function, and requires -STA mode) — you have to specify it as a ScriptBlock. So now that we know this, we can rewrite our first example like this:
Just for the record, the simplest Boots program would just be a simple popup dialog to put some text in a Window, like: Boots { $msg } …

StackPanels are awesome. So are WrapPanels. Try that code with a WrapPanel instead of a StackPanel and see what the difference is. This brings up another point: those positional parameters we mentioned earlier: Content, Children, Items, Blocks, and Inlines, are also set to accept the value from the pipeline. Not only that, but they are intelligent about whether or not the content model accepts multiple items! So we can actually rewrite that script like this, and get the same results:
Now we’re really onto something! Read the rest of this entry »
Awhile back I wrote a series of posts about WPF From PowerShell From PowerShell” which were about how you could load XAML in previous PowerShell 2 CTPs to create WPF user interfaces … a few people have mentioned loading XAML in PowerBoots, and a couple of people have posted other samples showing XAML even since I published the most recent release, so I figure it’s time to point out that you really can load that XAML into Boots, and get all the threading and other support.
Just for fun, I’m going to rehash an earlier post about updating windows to show how you can go about this using PowerBoots, and hopefully show that it’s a little easier (and a lot more async). Compare and contrast the code in this article with that one, just for fun.
Unlike the original article, most this code (except where explicitly mentioned) works on either PowerShell v2 with PowerBoots, or PowerShell 1.0 with PoshWPF, a snapin that is part of the PowerBoots module but is also released separately… Also, unlike those previous posts, this does not require you to be running PowerShell.exe with the -STA switch, since the New-BootsWindow cmdlet takes care of threading for us.
Read the rest of this entry »WPF uses a concept called “Attached Properties” to handle certain things, like when you put controls into a DockPanel. Basically, anything you put inside a DockPanel has a property “Dock” which you can set … but because the property is actually defined by the DockPanel, it doesn’t show up in PowerBoots, so you can’t just say -Dock "Bottom" when you create the child items … at least, not yet.
I’m still thinking about the best way for me to expose this in PowerBoots, because the problem is that attached properties can get attached several ways, and not just on direct children of an element. So I wanted to show you a way that you can do it for now so you can at least use the DockPanel effectively:
Here’s what I’m thinking about for the next release of PowerBoots (you can take this and use it now, if you like it, but I’m really looking for, uhm … better ideas). Basically, I have written a function: Set-AttachedProperty, which takes an attached property and a value, and passes through the element on the pipeline. You may want to use this in conjunction with the module I published awhile back for creating type accelerators, because it lets you run a line like this:
Which will let you substitute [DockPanel] for [System.Windows.Controls.DockPanel] … and of course, you can use it for all the types you want to use attached properties from, and it’s a real lifesaver if you need to use a bunch of them. Of course, in this particular example, we really only need to use a single attached property, so it’s enough to define that property ahead of time:
Then you can use the Set-AttachedProperty function through an alias sap, and rewrite that huge block above like this:
Pretty slick, right? And it will even print out the list of values in the error message if you invoke it with an invalid value against an enum property like dock: sap $DockProperty "" … The problem I have with it is that you have to predefine your $DockProperty variable, and you can’t just define it against the root class. So I’m trying to find a way to tweak the dynamic property generation to make it so that the pipe into | sap $DockProperty Bottom can just be a parameter to the original element: -Dock Bottom … if I can’t find that, in the worst case scenario, I’ll just add an -AttachedProperties parameter with a hashtable of $DockProperty,“Bottom” or something … what do you think?
In any case, here’s the sap function, for now, and remember to use it as part of the pipeline:
This release of PowerBoots is the most exciting release software I’ve cranked out in awhile. It finally has almost all of the features that I have thought of so far (we’re still missing proper support for attached properties).
-Async in their own threads, or inline in PoshConsole, or as synchronous dialogs that return values when they close.You can read the “and much much more” between the lines right?
Read the rest of this entry »Once I started playing with the new ability, introduced in PowerBoots 0.0.4 to easily add support for new graphical controls to PowerBoots, I found all sorts of fun widgets out there in open-source land. I’ll write about a few of them in the future, but for now I’m just going to stick with Visifire. After playing with a few examples, I finally got around to actually trying to create the graphs I needed at work which were the main source of motivation for trying to do Visifire from PowerShell anyway …
The problem was, half of the need we have for graphs is to throw them up on a web-server … so I needed a way to take the WPF window, and capture the controls and visuals as an image. Basically, render the WPF control to a bitmap image, instead of to the screen. To cut a long story short, I figured it out of course — why else would I be writing this? (get it here).
So the new version of PowerBoots includes the Out-BootsImage function (aliased as BootsImage and “obi”), which basically is designed to take the filename of an image, and a boots visual element, and create a screenshot. It can generate bmp, gif, jpg, png, tiff, and even Microsoft’s new wdp format, or it can output to clipboard.

It’s late, so I’m not going to write any more about this … the bottom line is, if you have been looking for a (free) way to generate graphs and charts to image files in PowerShell, this will work for you: go grab Visifire, check out their gallery for inspiration, and start churning out graphs! Just for fun, here are the samples from the help documentation (except, this is the actual script I ran, including the upload code) with screen-shots …
When producing images of Visifire charts using this method, it is absolutely critical that you must specify -Animation $false because otherwise you will consistenly produce images of empty charts (since by default Visifire animates all of the bars onto the screen right after the SourceInitialized event that I use to capture the image). Oh, and if you need to remove the Visifire.com watermark, there is a -watermark $false parameter on the Chart element, which turns it off.

This is the fourth release of the PowerBoots module for PowerShell 2 (Download – 7z). PowerBoots is a framework for creating WPF GUIs from PowerShell, and this latest release brings a couple of bug fixes and two new features.
The biggest change in PowerBoots 0.0.4 is that tab-completion for parameters works in the shell.
Behind the scenes what has happened is that I’ve discovered that in the current CTP3 release of PowerShell 2, Dynamic Parameter sets are not handled correctly for aliases, and the Get-Command for aliases of functions doesn’t return the same set of parameters as it does on the function itself. The result is that Tab-Completion for dynamic parameters doesn’t work on aliases (neither the built-in tab completion, nor MoW’s PowerTab). I wrote up a bug against that, but I also found that I can work around it by creating hundreds of functions (all pointed at the same script-block), instead of hundreds of aliases (all pointed at the same function).
This means the PowerBoots commands show up by default when you run Get-Command. Incidentally, this means that the first time you run Get-Command after you Import-Module PowerBoots you incur a huge penalty (17 seconds on my machine) while Get-Command caches all the dynamic parameter information about the functions. NOTE: because of the DynamicParam bug, I’ve ditched aliases altogether for this particular project and am generating two functions for each element/type in PowerBoots: the full New-Namespace.Type version, and a “Type” alias when possible. Trust me when I say: “it’s worth it” ... with the backing scriptblock, there’s virtually no difference between the two approches in terms of resources (other than the aforementions hit on Get-Command).
The second big change (and the one which I hope will have the biggest long-term impact) is that you can now import your own WPF control libraries into PowerBoots. This means that you can, for example, go get the open source Visifire charting library, extract their WPFVisifire.Charts library into your PowerShell folder, and use it like so:
I’m almost ready to release a version of Out-WPF which will work on both my PoshConsole host (embedding in the host when appropriate) and on PowerShell.exe, both in CTP3 and in v1 … but since Jeffrey outed my little video demo, I figured I might as well share it here. Read the rest of this entry »
I wrote yesterday about the WPF Snap-To Behavor that I created, and showed you how simple it is, but I skipped over where the magic happens, so I thought I’d go through how I created the Native Behaviors collection class, because there are a few cool tricks in here that I wanted to share with WPF developers at large (even if you’re not interested in hooking the Window Procedure).
The framework for Native Bahaviors is made up of just two classes, the first of which is basically 3 lines of code.
NativeBehavior is the abstract base class for behaviors, and consists of just definitions for the mandatory abstract GetHandlers() method (where you return an IEnumerable collection of mappings from Window Messages to your delegate methods) and the two optional (virtual) methods AddTo and RemoveFrom which are called when your behavior is initially added to a window (generally before the Window is initialized).
NativeBehaviors is an ObservableCollection of NativeBehaviors, obviously
. But it’s ever so much more than that. First of all, it has the NativeBehaviors attached property, but it also has the code for actually hooking a WPF window to get the Window Messages, and a WndProc which processes each message against the mappings retrieved from the various NativeBehaviors that have been registered.
Lets start with the attached dependency property. There’s a very clever (and problematic) trick in the way this property is exposed. If you look at this code, you’ll see I create a private NativeBehavior dependency property, and then create public Get/Set accessors for “Behavior” which just call the NativeBehavior property. The reason for this is that if the dependency property is public, or if the public accessors even have the same name … the XAML parser finds the dependency property and uses it directly (bypassing the get/set accesors), which means you have to have an extra element in your XAML markup to initialize the NativeBehaviors collection, or you get something like this screenshot.
So instead, we hide the dependency property, and supply a getter which is backed by the dependency property. I should not that although this works great in the .Net Framework, it’s not recognized properly by all of the tools (including Resharper 4.1 and even Expression Blend), so you may have to fiddle with things.
There’s a little more to it in the actual class source code, I’m glossing over the simplest parts, and leaving out all the XML documentation comments too. We override the CollectionChanged event so that we can hook new Behaviors as they arrive, and we make sure to hook the WndProc whenever the Target Window is set:
And finally, the last part of the puzzle is my actual WndProc implementation, which has a minor drawback in that we can hypothetically have multiple behaviors which process the same window message … and may each return a different value (which we cannot reconcile). For now I’m just returning the last (non-zero) result (in actuality, all of the behaviors I’ve written thus far return zero).
That pretty much covers the framework. The actual behaviors can be fairly simple like my Snap-To behavior (which is actually too simple), or extremely complex like my latest behavior, which is a port Joe Castro’s custom Window ‘Chrome’ to my behavior framework, and I’m hoping some of you will choose to write new ones and submit them as patches to the CodePlex project (for now, I’m just piggybacking it on the PoshConsole project). But in any case, the latest code is available via subversion on CodePlex, and you can download today’s snapshot here.
There are many desirable behaviors for Windows applications that are just much harder to do than they should be with the tools that Microsoft has provided in the .Net Framework. In WPF, many of these behaviors are even harder to create than in Windows Forms because the necessary hooks take a bit more work to write (thanks to the fact that there’s no window handles, so dropping down to “Native” code is harder. Luckily, WPF Attached Properties give us a whole new way to reuse these behaviors once they’re written.
I’ve started working on a few classes I’m calling NativeBehaviors, because they rely on intercepting the native Window Message processing, and I’ve put together a simple framework to let me write them, which I thought I would share. The first one I wrote is a SnapToBehavior, which implements a feature that people seem to be constantly re-implementing in apps. Basically, it makes a window snap to the screen edge when it gets close (and prevents them from being moved off-screen). I’ve also written a Global HotkeysBehavior which lets you register Hotkeys that work whenever your app is running (even if another app is active) so you can create a Hotkey to hide your app and show it, or whatever.
In the rest of this article I’ll show you how to achieve this in WPF using my base NativeBehavior class, and how to use it on a Window. Since some of you won’t really care how it works, let’s start with:
Step 1. Add a reference to the Huddled.Wpf.Interop library.
Step 2. Add my Xml namespace to your root Window element
Step 3. Paste three lines from below….
I should point out the “SnapDistance” property of the SnapToBehavior is actually a WPF “Thickness” which lets you specify the distance from the screen edge as a single number to use on all sides, or as a separate number for each side: Left, Top, Right, Bottom. And that’s pretty much all there is to know.
The implementation of the SnapToBehavior is actually ridiculously simple, given the NativeBehavior framework. I simply created a SnapToBehavior class which derives from NativeBehavior, and implemented the single mandatory method:
When my new behavior is added to the Behaviors collection, my handler will be registered, and whenever the WM_WINDOWPOSCHANGING message arrives, it will be called. Now I defined a DependencyProperty for the SnapDistance, so that you could set that in XAML. It’s extremely simple, and VisualStudio has a built-in snippet for dependency properties, but here’s the code:
Once I have that, the last piece of the puzzle is to actually handle the window position changing message (think of it as an event, if you’re not used to Win32 message-based programming).
The basics of handling WM_WINDOWPOSCHANGING is that you get a structure passed in which has the proposed position of the Window, (including it’s z-index related to other apps) and you can basically tweak that however you like. Obviously there are lots of possibilities for this single message: always-on-bottom windows, undraggable windows, etc., but in our case we’re just concerned about how close we are to the edge.
We use the SystemParameters class to get the VirtualScreenLeft, VirtualScreenTop, and VirtualScreenWidth and VirtualScreenHeight which define the rectangle we’ll use for snapping. In the case of non-rectangular arrangements of multiple monitors this isn’t quite sufficient, but for our example anything more would be a distraction. Then we just check to see if the proposed position is within the “SnapDistance” of any of the edges, and if so, we change the position to be against the edge. That’s really all there is to it.
If you look at the code example below you’ll see I have to “Marshal” the WindowPosition structure in and out of an IntPtr which is passed in the WindowMessage … that’s the downside of intercepting window messages that the framework doesn’t already translate for us, but in this particular case, it’s actually fairly trivial.
If you’d like, you can download the current Huddled Interop for WPF library right now, or you can check out the source from CodePlex SVN or just download the most recent commit (You are only interested in the “Huddled” project which is in the “trunk”, not the “trunk-3.5”). The source is licensed freely under the BSD or GPL v2 (and a few other licenses, see the top of the source code files).
Either way you’ll get not just the SnapToBehavior but also the global HotkeysBehavior, and the Native Behaviors framework which I’ll write more about later, but for now, in case you want to try to use it, here’s an example using both the SnapTo and HotkeysBehavior (you can find this in the GlobalHotkeys demo project, which includes some sample code for handling hotkey conflicts). Enjoy.