Changes

Creating GUIs in Windows PowerShell 1.0 with WinForms

1,883 bytes added, 19:12, 12 December 2008
no edit summary
$button = New-Object Windows.Forms.Button
# $button.text = "Click Here!"
$button.add_click({do_exit})
<pre>
$button.text = "Click Here!"
</pre>
 
Similarly, we could set the title of the form using the form object's ''text'' property:
 
<pre>
$form.text = "PowerShell WinForms Example"
</pre>
 
== A More Complex Example ==
 
Now that have seen a simple GUI created in Windows PowerShell and covered some of the basic techniques we can create a slightly more complex GUI. The following script creates a GUI containing a label, button and text field. An event handler is configured on the button such that when it is clicked the text is extracted from the text field and used to construct a message which is then displayed on the label control. Note the creation of Drawing.Point objects to configure the size and location of controls on the form:
 
<pre>
# Load the Winforms assembly
[reflection.assembly]::LoadWithPartialName( "System.Windows.Forms")
 
# Create the form
$form = New-Object Windows.Forms.Form
 
#Set the dialog title
$form.text = "PowerShell WinForms Example"
 
# Create the label control and set text, size and location
$label = New-Object Windows.Forms.Label
$label.Location = New-Object Drawing.Point 50,30
$label.Size = New-Object Drawing.Point 200,15
$label.text = "Enter your name and click the button"
 
# Create TextBox and set text, size and location
$textfield = New-Object Windows.Forms.TextBox
$textfield.Location = New-Object Drawing.Point 50,60
$textfield.Size = New-Object Drawing.Point 200,30
 
# Create Button and set text and location
$button = New-Object Windows.Forms.Button
$button.text = "Greeting"
$button.Location = New-Object Drawing.Point 100,90
 
# Set up event handler to extarct text from TextBox and display it on the Label.
$button.add_click({
 
$label.Text = "Hello " + $textfield.text
 
})
 
# Add the controls to the Form
$form.controls.add($button)
$form.controls.add($label)
$form.controls.add($textfield)
 
# Display the dialog
$form.ShowDialog()
</pre>