Dec
2
Written by:
Oisin Grehan
12/2/2007 4:49 PM
Using Windows Forms controls in PowerShell is a tricky thing, because it only supports very simple event handling. However, some time ago I wrote a Snap-In to allow anyone to work with .NET events, even asynchronous ones. You can download it from my PSEventing CodePlex project; it comes with full help via the normal PowerShell mechanisms of -? and get-help. Examples are also available online on how to use the project for more complex scenarios. Here's simple demonstration of autogenerating a listbox control filled with choices given as arguments to a simple script:
-
- $choice = .\get-choice.ps1 "one","two","three"
And here is the source to the get-choice.ps1 script itself. This requires PSEventing 1.0 or 1.1 Beta.
-
-
-
-
- param([string[]]$choices = $(throw "please supply a string array of choices"))
-
- if ($choices.length -eq 0) {
- Write-Warning "cannot be a zero length array."
- return
- }
-
-
- $form = new-object windows.forms.form
- $form.Text = "Choose..."
- $form.MinimizeBox = $false
- $form.MaximizeBox = $false
- $form.AutoSize = $true
- $form.AutoSizeMode = "GrowAndShrink"
-
-
- $listbox = new-object windows.forms.listbox
- $choices | % { [void]$listbox.items.add($_) }
-
- $form.controls.Add($listbox)
-
-
- Connect-EventListener -VariableName listbox -EventName SelectedIndexChanged -Verbose
-
-
- Connect-EventListener -VariableName form -EventName Closed -Verbose
-
- $form.Show()
-
-
- $event = Get-Event -Wait
-
-
- write-host ($event | ft -auto | out-string)
-
- $form.Dispose()
-
- $choice = $listbox.SelectedItem
-
-
- $form = $null
- $listbox = $null
-
-
- if ($event.Name -eq "SelectedIndexChanged") {
- $choice
- } else {
- $null
- }
Have fun!
download script: get-choice.ps1
Tags: