How to display a Windows Form using PowerShell

by Doug Finke on January 28, 2011

in IronPython,IronRuby,Microsoft,PowerShell,WinForms,Windows Forms

I came across a Microsoft IronPython post showing code displaying a Windows form. I copied and pasted the IronPython code into the PowerShell ISE (Integrated Scripting Environment) then:

  • Did an Add-Type on Systems.Windows.Forms
  • Added some dollar signs ‘$’
  • Changed ‘new’ to New-Object

The form is up and running. Clicking on the button adds one to a counter and displays it in the title bar.

A Non-Binary Deployment

Cool thing, if you have Windows 7 installed, you have PowerShell installed. You can copy and paste this code straight away into the PowerShell console and it will work.

You could even email this snippet and as long as the receiver has PowerShell installed it would work.

The Code

Add-Type -AssemblyName System.Windows.Forms            

$f               = New-Object System.Windows.Forms.Form
$b               = New-Object System.Windows.Forms.Button
$f.StartPosition = "CenterScreen"
$b.Text          = "Hello World"
$b.Location      = New-Object System.Drawing.Point(250,100)
$f.Width         = 561            

$f.Controls.Add($b)
$count = 0
$b.add_click({ $f.Text = ($count += 1) })
$f.ShowDialog() | Out-Null

The Form

image

Share

{ 3 comments… read them below or add one }

Charlie Robbins 01.29.11 at 1:36 pm

Really Doug? C’mon …. ARE YOU READY FOR SOME JAVASCRIPT MOTHER $&%*#!?

3ntropy 07.29.11 at 11:17 pm

How to avoid full namespace qualification over and over again?

System.Windows.Forms.Button.blAH BLAH

Doug Finke 07.31.11 at 7:45 pm

Good question. I tried this but no luck.

$ns = [System.Windows.Forms]
$b = New-Object $ns.Button

Leave a Comment

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>