Saturday, May 30, 2015

#76 : Using Choice Box in Powershell

I got an interesting requirement to allow users choose from a list. The list will be dynamic and will display all items of the file in a drop down list.

Preparation:
1. Create an empty file called list.txt.
2. Add below entries to the file:
ABC
XYZ
PQR
RST
UVX
123
3. Create script and paste below code:

function showDialog([string]$file) 
{
 [void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
 [void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing") 

 $objForm = New-Object System.Windows.Forms.Form 
 $objForm.Text = "Choice-Box"
 $objForm.Size = New-Object System.Drawing.Size(300,200) 
 $objForm.StartPosition = "CenterScreen"

 $objForm.KeyPreview = $True
 $objForm.Add_KeyDown({if ($_.KeyCode -eq "Enter") 
  {
   $x=$objListBox.SelectedItem;$objForm.Close()}
  })
  
 $objForm.Add_KeyDown({if ($_.KeyCode -eq "Escape") 
  {$objForm.Close()}})

 $OKButton = New-Object System.Windows.Forms.Button
 $OKButton.Location = New-Object System.Drawing.Size(75,120)
 $OKButton.Size = New-Object System.Drawing.Size(75,23)
 $OKButton.Text = "OK"
 $OKButton.Add_Click({$x=$objListBox.SelectedItem;$objForm.Close()})
 $objForm.Controls.Add($OKButton)

 $CancelButton = New-Object System.Windows.Forms.Button
 $CancelButton.Location = New-Object System.Drawing.Size(150,120)
 $CancelButton.Size = New-Object System.Drawing.Size(75,23)
 $CancelButton.Text = "Cancel"
 $CancelButton.Add_Click({$objForm.Close()})
 $objForm.Controls.Add($CancelButton)

 $objLabel = New-Object System.Windows.Forms.Label
 $objLabel.Location = New-Object System.Drawing.Size(10,20) 
 $objLabel.Size = New-Object System.Drawing.Size(280,20) 
 $objLabel.Text = "Please choose any of the below :"
 $objForm.Controls.Add($objLabel) 

 $objListBox = New-Object System.Windows.Forms.ListBox 
 $objListBox.Location = New-Object System.Drawing.Size(10,40) 
 $objListBox.Size = New-Object System.Drawing.Size(260,20) 
 $objListBox.Height = 80

 $items = gc $file | where { $_ -ne "" }
 
 foreach ( $item in $items) 
 {
  [void] $objListBox.Items.Add($item)
  
 } 

 $objForm.Controls.Add($objListBox) 

 $objForm.Topmost = $True

 $objForm.Add_Shown({$objForm.Activate()})
 [void] $objForm.ShowDialog()

 $x

} 


showDialog .\list.txt 


Once your run it, you will get a popup like below:


That's it! You can see the value of $x can be used further in any place of your code.

Hope you liked this article. Send your comments and suggestions to me...
Enjoy!

3 comments:

  1. May I know Where the selected entry is saved from the objlistbox ?

    I mean the variable name of it

    ReplyDelete
  2. In $x its not storing... I dont know why..

    ReplyDelete

#112: How to handle xml document in Powershell?

 In PowerShell, you can handle XML data using various cmdlets and methods provided by the .NET Framework. Here's a basic guide on how to...