I have a tablelayoutpanel that I have autoscroll turn on for. I would like to completely hide the horizontal scroll bar but do not see how this is possible. It seems like I could set VScroll to true and HScroll to false but I am unsure how to access these properties from the tablelayoutpanel object. How can I hide the horizontal scroll bar?
[CmdletBinding()]
Param()
Set-StrictMode -Version 2
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing") | Out-Null
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") | Out-Null
Write-Verbose "Create the main form"
$form = New-Object Windows.Forms.Form
$form.Size = New-Object Drawing.Size #(900, 600)
$form.SuspendLayout()
$dataSize = 70
$dataHeight = 20
$volumeSize = 280
$dp = New-Object Windows.Forms.TableLayoutPanel
$addButton = New-Object Windows.Forms.Button
$addButton.Text = "Add"
$addButton.name = "outputButton"
$addButton.Add_Click({Add-Row})
$addButton.Location = New-Object System.Drawing.Point(0,500)
$correctedWidth = 0
Function Add-Row ($txt) {
write-verbose "add row"
$script:dp.RowCount++
$zeroBasedRow = $dp.RowCount - 1
write-verbose $zeroBasedRow
for ($i=0; $i -lt 7; $i++) {
$label = New-Object System.Windows.Forms.Label
$label.TextAlign = "MiddleCenter"
$label.Text = "0"
$label.Font = "Verdana, 9pt"
$label.Size = "$dataSize,$dataHeight"
$label.BackColor = "Transparent"
if ($i -eq 0) {
$label.Size = "$correctedWidth,$dataHeight"
if ($txt -eq $null){
$label.Text = "12345678901234567890123456789012"
} else {
$label.Text = $txt
}
}
$dp.Controls.Add($label,$i,$zeroBasedRow)
}
}
Function Create-Data-Panel ($width, $height, $correction) {
Write-Verbose "Create the panel that holds the data"
$dataPanel = New-Object Windows.Forms.TableLayoutPanel
$dataPanel.Size = New-Object Drawing.Size #($width,$height)
$dataPanel.AutoScroll = $true
#$dataPanel.VerticalScroll.Enabled = $true
#$dataPanel.VerticalScroll.Visible = $true
#$dataPanel.HorizontalScroll.Enabled = $false
#$dataPanel.HorizontalScroll.Visible = $false
$dataPanel.BackColor = "Transparent"
$dataPanel.CellBorderStyle = "None"
$dataPanel.RowCount = 0
$dataPanel.ColumnCount = 7
$script:correctedWidth = $volumeSize - $correction
return $dataPanel
}
$hght = $form.size.height * 3/4
$dp = Create-Data-Panel 760 300 4
for ($j=0; $j -lt 50; $j++){ # LINE OF INTEREST!!!!!!
$txt = "$j 12345678901234567890123456789012"
Add-Row $txt
}
$form.Controls.Add($dp)
$form.Controls.Add($addButton)
$form.Add_Shown( { $form.Activate() } )
$form.ResumeLayout()
$form.StartPosition = "CenterScreen"
$form.ShowDialog()
Notice that AutoScroll is on. If you run this script as is the TableLayoutPanel will only show the vertical scroll bar; push the "Add" button as many times as you want and you will see the table has new entries at the end and the scroll bar remains only showing the vertical scroll bar. The problem is that the TableLayoutPanel I am working with does not have ANY initial data on it so essentially the "LINE OF INTEREST!!!!!!" becomes a 0 for the $j bounding value. Change that value to zero so the line reads "for ($j=0; $j -lt 0; $j++){ # LINE OF INTEREST!!!!!!" and then run the script (notice the table is empty. Press the "Add" button (notice no scroll bars show up until they are needed which is not a problem). Fill the table so that the vertical scroll bar is needed and you will see that BOTH the vertical and horizontal scroll bars appear – I ONLY want the vertical scroll bar not the horizontal – so my question is how to hide the horizontal scroll bar? Thanks!
The problem is that the scroll bars extend inward in the panel, decreasing the available space for the embedded controls.
Thus, once a vertical scrollbar is shown due to .AutoScroll being set to $true, there isn't enough horizontal space for the labels anymore, and the horizontal scrollbar is shown too.
With .AutoScroll set to $true, you cannot manually turn the scrollbars off with statements such as .HorizontalScrollBar.Visble = $false - such attempts are ignored.
I'm sure there are better solutions, but here's a quick fix, that:
widens the panel by the width of the vertical scroll bar once the latter is shown, which causes .AutoScroll ultimately not to show a horizontal scrollbar,
but note that that the horizontal scrollbar will flash visibly before it is hidden when the row that causes the vertical scroll bar to show is added.
Function Add-Row ($txt) {
write-verbose "Adding row with index $($dp.RowCount)"
$dp.SuspendLayout()
$dp.RowCount++
for ($i=0; $i -lt 7; $i++) {
$label = New-Object System.Windows.Forms.Label
$label.TextAlign = "MiddleCenter"
$label.Text = "0"
$label.Font = "Verdana, 9pt"
$label.Size = "$dataSize,$dataHeight"
$label.BackColor = "Transparent"
if ($i -eq 0) {
$label.Size = "$correctedWidth,$dataHeight"
if ($txt -eq $null){
$label.Text = "12345678901234567890123456789012"
} else {
$label.Text = $txt
}
}
$dp.Controls.Add($label, $i, $dp.RowCount - 1)
}
$dp.ResumeLayout()
# If a horizontal scrollbar has just appeared as a follow-on effect
# of AutoScroll having just turned on the vertical scrollbar,
# widen the panel by the width of the vertical scrollbar
# so as to make the horizontal scrollbar disappear again.
if ($dp.HorizontalScroll.Visible) {
$dp.width += [System.Windows.Forms.SystemInformation]::VerticalScrollBarWidth
}
}
On a side note: using both [void] and | Out-Null in the statements that load the assemblies is unnecessary and will actually fail in PSv5 (possibly 4 or 3 too).
Related
I'm trying to create clicks for right mouse button which are specific to each item in the listview to be able to execute commands on remote pc. I just don't know how assign the separate context menu to a specific ListViewItem.
I have tried to create form also with an array but I have bumped to the same problem and I don't know how to formulate the problem to search for it on internet.
Thanks for help!
Here is the code:
## Set up the environment
Add-Type -AssemblyName System.Windows.Forms
$LastColumnClicked = 0 # tracks the last column number that was clicked
$LastColumnAscending = $false # tracks the direction of the last sort of this column
## Create a form and a ListView
$Form = New-Object System.Windows.Forms.Form
$ListView = New-Object System.Windows.Forms.ListView
## Configure the form
$Form.Text = "Computer List"
## Configure the ListView
$ListView.View = [System.Windows.Forms.View]::Details
$ListView.Width = $Form.ClientRectangle.Width
$ListView.Height = $Form.ClientRectangle.Height
$ListView.Anchor = "Top, Left, Right, Bottom"
# Add the ListView to the Form
$Form.Controls.Add($ListView)
# Add columns to the ListView
$ListView.Columns.Add("Computer Name", -2) | Out-Null
$ListView.Columns.Add(" Test") | Out-Null
# Add list items
$contextMenuStrip = [System.Windows.Forms.ContextMenuStrip]#{}
$listView.Font = 'Microsoft Sans Serif,10'
##Computer1##
$ListViewItem = New-Object System.Windows.Forms.ListViewItem("computer1")
$click1 = {Invoke-Command -UseSSL -ComputerName computer1 }
$click2 = {Invoke-Command -UseSSL -ComputerName computer1 }
$item1 = $contextMenuStrip.Items.Add("Run 1")
$item1.add_Click($click1)
$item2 = $contextMenuStrip.Items.Add("Run 2")
$item2.add_Click($click2)
$listView.Add_MouseClick({param($sender,$e)
if ($e.Button -eq [System.Windows.Forms.MouseButtons]::Right){
if ($listView.FocusedItem.GetBounds(
[System.Windows.Forms.ItemBoundsPortion]::Entire).Contains($e.Location)){
$contextMenuStrip.Show([System.Windows.Forms.Cursor]::Position)
}
}
})
$ListView.Items.Add($ListViewItem) | Out-Null
##computer2##
$contextMenuStrip = [System.Windows.Forms.ContextMenuStrip]#{}
$ListViewItem = New-Object System.Windows.Forms.ListViewItem("computer2")
$click1 = {Invoke-Command -UseSSL -ComputerName computer2 }
$click2 = {Invoke-Command -UseSSL -ComputerName computer2 }
$item1 = $contextMenuStrip.Items.Add("Run 3")
$item1.add_Click($click1)
$item2 = $contextMenuStrip.Items.Add("Run 4")
$item2.add_Click($click2)
$listView.Add_MouseClick({param($sender,$e)
if ($e.Button -eq [System.Windows.Forms.MouseButtons]::Right){
if ($listView.FocusedItem.GetBounds(
[System.Windows.Forms.ItemBoundsPortion]::Entire).Contains($e.Location)){
$contextMenuStrip.Show([System.Windows.Forms.Cursor]::Position)
}
}
})
$ListView.Items.Add($ListViewItem) | Out-Null
## Set up the event handler
$ListView.add_ColumnClick({SortListView $_.Column})
## Event handler
function SortListView
{
param([parameter(Position=0)][UInt32]$Column)
$Numeric = $true # determine how to sort
# if the user clicked the same column that was clicked last time, reverse its sort order. otherwise, reset for normal ascending sort
if($Script:LastColumnClicked -eq $Column)
{
$Script:LastColumnAscending = -not $Script:LastColumnAscending
}
else
{
$Script:LastColumnAscending = $true
}
$Script:LastColumnClicked = $Column
$ListItems = #(#(#())) # three-dimensional array; column 1 indexes the other columns, column 2 is the value to be sorted on, and column 3 is the System.Windows.Forms.ListViewItem object
foreach($ListItem in $ListView.Items)
{
# if all items are numeric, can use a numeric sort
if($Numeric -ne $false) # nothing can set this back to true, so don't process unnecessarily
{
try
{
$Test = [Double]$ListItem.SubItems[[int]$Column].Text
}
catch
{
$Numeric = $false # a non-numeric item was found, so sort will occur as a string
}
}
$ListItems += ,#($ListItem.SubItems[[int]$Column].Text,$ListItem)
}
# create the expression that will be evaluated for sorting
$EvalExpression = {
if($Numeric)
{ return [Double]$_[0] }
else
{ return [String]$_[0] }
}
# all information is gathered; perform the sort
$ListItems = $ListItems | Sort-Object -Property #{Expression=$EvalExpression; Ascending=$Script:LastColumnAscending}
## the list is sorted; display it in the listview
$ListView.BeginUpdate()
$ListView.Items.Clear()
foreach($ListItem in $ListItems)
{
$ListView.Items.Add($ListItem[1])
}
$ListView.EndUpdate()
}
## Show the form
$Response = $Form.ShowDialog()
})
$ListView.Items.Add($ListViewItem) | Out-Null
I have a form with a listview for which I have a right click context menu. I'd like the menu to only appear if the right clikc is above the selected item in the listview - at the moment it appears anywhere in the listview windows and even if nothing is selected.
Add-Type -AssemblyName System.Windows.Forms
$form = New-Object System.Windows.Forms.Form
$form.Text = "Foo"
$form.Size = '400,400'
$CMitemEnable = New-Object System.Windows.Forms.ToolStripMenuItem
$CMitemEnable.Text = 'Enable'
$CMitemDisable = New-Object System.Windows.Forms.ToolStripMenuItem
$CMitemDisable.Text = 'Disable'
$lvcontextmenu = New-Object System.Windows.Forms.ContextMenuStrip
$lvcontextmenu.ShowImageMargin = $false
$lvcontextmenu.Items.AddRange(#($CMitemEnable,$CMitemDisable))
$listviewbox = New-Object System.Windows.Forms.ListView
$listviewbox.View = [System.Windows.Forms.View]::Details
$listviewbox.Location = '15,20'
$listviewbox.Size = '340,150'
$listviewbox.Columns.Add('Host',180) | Out-Null
$listviewbox.FullRowSelect = $true
$listviewbox.MultiSelect = $false
# $listviewbox.ContextMenuStrip = $lvcontextmenu
$InfoText = New-Object System.Windows.Forms.TextBox
$InfoText.Location = '15,180'
$InfoText.Size = '340,120'
$InfoText.Multiline = $true
$InfoText.ScrollBars = "Vertical"
$InfoText.ReadOnly = $true
$form.Controls.AddRange(#($listviewbox,$InfoText))
$listviewbox.Items.AddRange(#('Foobar1','foobar2'))
$listviewbox.Add_MouseDown({
$listviewbox.contextmenustrip = $null
If($listviewbox.SelectedItems.Count){
$listviewbox.contextmenustrip = $lvcontextmenu
$InfoText.AppendText("`r`n" + ($this.SelectedItems[0].Text))
}
Else {
$InfoText.AppendText("`r`nNothing selected")
$listviewbox.contextmenustrip = $null
}
})
# Show form
$form.ShowDialog() | Out-Null
$form.Dispose()
I've not done context menus before and can't see for the life of me how to implement the event handler for this - there's examples for C etc but can someone point me in the right direction for Powershell please?
Considering the following points:
Don't set ContextMenuStrip for the ListView
Handle MouseClick event, so first the item will be selected, then your code run. (As an alternative, if you prefer mouse down, then you need to need to put your logic in BeginInvoke to make sure it will run after selection of item.)
Using GetBound method of the selected item and e.Location, check if the clicked location is inside the item rectangle
Show the ContextMenuStrip using Show by passing Cursor.Position
Here is a working example:
Add-Type -AssemblyName System.Windows.Forms
$form = New-Object System.Windows.Forms.Form
$form.Text ="Test"
$form.Controls.AddRange(#(
($listView1 = [System.Windows.Forms.ListView] #{
Dock = [System.Windows.Forms.DockStyle]::Fill;
FullRowSelect = $true;
View = [System.Windows.Forms.View]::Details;
})
))
$contextMenuStrip1 = [System.Windows.Forms.ContextMenuStrip]#{}
$listView1.Columns.Add("C1") | Out-Null
$listView1.Columns.Add("C2") | Out-Null
$listView1.Items.Add("Item1") | Out-Null
$listView1.Items.Add("Item2") | Out-Null
$contextMenuStrip1.Items.Add("Menu 1") | Out-Null
$contextMenuStrip1.Items.Add("Menu 2") | Out-Null
$listView1.Add_MouseClick({param($sender,$e)
if ($e.Button -eq [System.Windows.Forms.MouseButtons]::Right){
if ($listView1.FocusedItem.GetBounds(
[System.Windows.Forms.ItemBoundsPortion]::Entire).Contains($e.Location)){
$contextMenuStrip1.Show([System.Windows.Forms.Cursor]::Position)
}
}
})
$form.ShowDialog() | Out-Null
$form.Dispose()
$contextMenuStrip1.Dispose()
Maybe there is a cleaner way, but this works for me:
First, remove line 22 ($listviewbox.ContextMenuStrip = $lvcontextmenu)
and then change the Click-handler for the $listviewbox into:
$listviewbox.Add_Click({
If($this.SelectedItems.Count){
$this.ContextMenuStrip = $lvcontextmenu
$InfoText.AppendText("`r`n" + ($this.SelectedItems[0].Text))
}
Else {
$this.ContextMenuStrip = $null
$InfoText.AppendText("`r`nNothing selected")
}
})
The following event handler works as intended - a combination of hints from both of you, thanks.
$listviewbox.Add_MouseUp({
$listviewbox.contextmenustrip = $null
If($listviewbox.SelectedItems.Count){
$listviewbox.contextmenustrip = $lvcontextmenu
$InfoText.AppendText("`r`n" + ($this.SelectedItems[0].Text))
}
Else {
$InfoText.AppendText("`r`nNothing selected")
$listviewbox.contextmenustrip = $null
}
})
I have a borderless winform (WPF is not an option) that I am trying to make draggable from an object that is serving as a custom sidebar. I have searched around and found some things that allow me to drag the sidebar within the form, but I need to be able to move $Form with the sidebar. Any thoughts? It seems like I will need to use Add-Type with some C# here.
Ok, since we don't have the code to your form, here's a demo for you. It is just a not-pretty borderless form that uses a label to demonstrate the various events needed to drag the entire form around. (in your case this would be the sidebar)
Add-Type -AssemblyName System.Windows.Forms
# set up some globals for dragging
$global:dragging = $false
$global:mouseDragX = 0
$global:mouseDragY = 0
#Form
$form = New-Object System.Windows.Forms.Form
$form.FormBorderStyle = "None"
$form.Font = New-Object System.Drawing.Font("Microsoft Sans Serif", 9.0, [System.Drawing.FontStyle]::Regular, [System.Drawing.GraphicsUnit]::Point)
$form.MinimumSize = New-Object System.Drawing.Size(456, 547)
$form.AutoScaleDimensions = New-Object System.Drawing.SizeF(7.0, 15.0)
$form.AutoScaleMode = [System.Windows.Forms.AutoScaleMode]::Font
$form.ClientSize = New-Object System.Drawing.Size(440, 509)
$form.ShowIcon = $false
$form.StartPosition = "CenterScreen"
$form.TopMost = $true
#lblDrag (this is the object used for dragging the form)
$lblDrag = New-Object System.Windows.Forms.Label
$lblDrag.Name = "lblDrag"
$lblDrag.BackColor = [System.Drawing.Color]::LightYellow
$lblDrag.Location = New-Object System.Drawing.Point(172, 226)
$lblDrag.Size = New-Object System.Drawing.Size(117, 27)
$lblDrag.Anchor = "Top","Right"
$lblDrag.BorderStyle = "FixedSingle"
$lblDrag.Text = "Drag form.."
$lblDrag.TextAlign = [System.Drawing.ContentAlignment]::MiddleCenter
# set the 'dragging' flag and capture the current mouse position
$lblDrag.Add_MouseDown( { $global:dragging = $true
$global:mouseDragX = [System.Windows.Forms.Cursor]::Position.X - $form.Left
$global:mouseDragY = [System.Windows.Forms.Cursor]::Position.Y -$form.Top
})
# move the form while the mouse is depressed (i.e. $global:dragging -eq $true)
$lblDrag.Add_MouseMove( { if($global:dragging) {
$screen = [System.Windows.Forms.Screen]::PrimaryScreen.WorkingArea
$currentX = [System.Windows.Forms.Cursor]::Position.X
$currentY = [System.Windows.Forms.Cursor]::Position.Y
[int]$newX = [Math]::Min($currentX - $global:mouseDragX, $screen.Right - $form.Width)
[int]$newY = [Math]::Min($currentY - $global:mouseDragY, $screen.Bottom - $form.Height)
$form.Location = New-Object System.Drawing.Point($newX, $newY)
}})
# stop dragging the form
$lblDrag.Add_MouseUp( { $global:dragging = $false })
# add a button so you will be able to close the form
$btnClose = New-Object System.Windows.Forms.Button
$btnClose.Name = "btnClose"
$btnClose.Anchor = "Top","Right"
$btnClose.Location = New-Object System.Drawing.Point(172, 454)
$btnClose.Size = New-Object System.Drawing.Size(117, 27)
$btnClose.Text = "&Close"
$btnClose.UseVisualStyleBackColor = $true
$btnClose.UseMnemonic = $true
$btnClose.DialogResult = [System.Windows.Forms.DialogResult]::OK
# add controls to the form
$form.Controls.Add($btnClose)
$form.Controls.Add($lblDrag)
$form.AcceptButton = $btnClose
# show the form and play around with the dragging label
$form.ShowDialog()
# when done, dispose of the form
$form.Dispose()
I'm working with the datagridview below. I'm trying to export the header names.
If you run this code and hit export, it will only output the column headers that the user can see initially (up to 'Model'), but it won't output 'Version' or 'Last Rebooted'. If you scroll to the right before hitting export then it will display all column names.
[void] [System.Reflection.Assembly]::LoadWithPartialName(“System.Windows.Forms”)
[void] [System.Reflection.Assembly]::LoadWithPartialName(“System.Drawing”)
$form = New-Object System.Windows.Forms.Form
$form.Size = New-Object System.Drawing.Size(1040,518)
$form.KeyPreview = $true
$form.StartPosition = ‘centerscreen’
$form.BackColor = 'MidnightBlue'
$form.Add_KeyDown({if($_.KeyCode -eq "Escape"){$form.Close()}})
$form.Text = "Dialog Box 3.4"
$form.Icon = [system.drawing.icon]::ExtractAssociatedIcon($PSHOME + "\powershell_ise.exe")
$form.MinimumSize = New-Object System.Drawing.Size(1040,518)
$buttonPanel4 = New-Object Windows.Forms.Panel
$buttonPanel4.Size = New-Object Drawing.Size #(290,70)
$buttonPanel4.Dock = "left"
$buttonPanel4.BackColor = 'MidnightBlue'
$DataGrid = New-Object System.Windows.Forms.DataGridView
$DataGrid.Location = New-Object System.Drawing.Size(298,29)
$DataGrid.Dock = "Fill"
$DataGrid.BorderStyle = ‘FixedSingle’
$DataGrid.ColumnHeadersDefaultCellStyle.Font = New-Object System.Drawing.Font(“segoe UI”,9.25)
$DataGrid.DefaultCellStyle.Font = New-Object System.Drawing.Font(“segoe UI”,9.25)
$DataGrid.AllowUserToAddRows = $false
$DataGrid.RowHeadersVisible = $false
$DataGrid.BackgroundColor = "White"
$DataGrid.ColumnCount = 10
$DataGrid.Columns[0].Name = ‘Machine’
$DataGrid.Columns[1].Name = ‘OperatingSystem’
$DataGrid.Columns[2].Name = ‘ServicePack’
$DataGrid.Columns[3].Name = ‘Architecture’
$DataGrid.Columns[4].Name = ‘Domain’
$DataGrid.Columns[5].Name = ‘PhysicalMemory’
$DataGrid.Columns[6].Name = ‘Manufacturer’
$DataGrid.Columns[7].Name = ‘Model’
$DataGrid.Columns[8].Name = ‘Version’
$DataGrid.Columns[9].Name = ‘Last Rebooted’
$DataGrid.Columns[9].Width = '140'
$Exportbutton = New-Object System.Windows.Forms.Button
$Exportbutton.Location = New-Object System.Drawing.Size(9,350)
$Exportbutton.Size = New-Object System.Drawing.Size(85,23)
$Exportbutton.Text = “Export-CSV”
$Exportbutton.BackColor = ‘LightGray’
$Exportbutton.UseVisualStyleBackColor = $true
$Exportbutton.Font = New-Object System.Drawing.Font(“segoe UI”,9)
$Exportbutton.Add_Click({
$columnNames = $null
$columnNames = $DataGrid.Columns[0].HeaderText
for($i = 1; $i -lt $DataGrid.ColumnCount;$i++){
$columnNames += ",$($DataGrid.Columns[$i].HeaderText)"
write-host $($DataGrid.Columns[$i].HeaderText) -ForegroundColor Magenta
}
write-host $columnNames -foregroundcolor cyan
})
$buttonPanel4.Controls.Add($Exportbutton)
$form.Controls.Add($DataGrid)
$form.Controls.Add($buttonPanel4)
$form.ShowDialog() | out-null
Is there a reason why this occurs and how can I export all the column names without scrolling to the right first?
As #pandemic points out, $buttonPanel4 is not defined/shown, also it appears you are setting the DataGrid.Dock property to Fill, which would cover up this button if it’s panel existed.
I do not have an answer for WHY the headers text returns an empty string until the header becomes visible in the data grid. I am guessing it is because the HeaderText property has not been set. I assume if the HeaderTexts property has not been set it will default to the columns Name property if needed. If you set each columns HeaderText property as you are with the Name property, this problem will not happen.
So either set each columns HeaderText or use its Name property as the code below shows.
I changed the code below to use the columns Name instead of the headers text and it appears to work correctly. In addition, I changed how the comma is inserted in to the $columnNames string variable to start the loop at index 0. Hope this helps.
$Exportbutton.Add_Click({
$columnNames = $null
for($i = 0; $i -lt $DataGrid.ColumnCount;$i++){
$columnNames += "$($DataGrid.Columns[$i].Name)"
if ($i -lt $DataGrid.ColumnCount - 1) {
$columnNames += ","
}
write-host $($DataGrid.Columns[$i].Name) -ForegroundColor Magenta
}
write-host $columnNames -foregroundcolor cyan
})
I want my GUI to be able to dynamically produce an event based on the user clicking either Radio Button 1 or Radio Button 2.
I have seen some good tutorials on this but its called during a click on a button. I want to call it OnClick of the radio button.
Here is the code I have so far:
#Load Assemblies
[System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") | Out-Null
[System.Reflection.Assembly]::LoadWithPartialName("System.Drawing") | Out-Null
$net = New-Object -ComObject Wscript.Network
Add-Type -AssemblyName System.Windows.Forms
#Create the Form
#Draw form
function SQLDoTasks{
$Form = New-Object System.Windows.Forms.Form
$Form.width = 800
$Form.height = 600
$Form.BackColor = "lightblue"
$Form.FormBorderStyle = [System.Windows.Forms.FormBorderStyle]::Fixed3D
$Form.Text = "Daily DBA Tasks"
$Form.maximumsize = New-Object System.Drawing.Size(525,350)
$Form.startposition = "centerscreen"
$Form.KeyPreview = $True
$Form.Add_KeyDown({if ($_.KeyCode -eq "Enter") {}})
$Form.Add_KeyDown({if ($_.KeyCode -eq "Escape")
{$Form.Close()}})
# Create a group that will contain your radio buttons
$MyGroupBox = New-Object System.Windows.Forms.GroupBox
$MyGroupBox.Location = '40,30'
$MyGroupBox.size = '400,150'
$MyGroupBox.text = "Specify the Sql environment?"
#Declare option buttons to allow user to select Dev or System Test
$RadioButton1 = New-Object System.Windows.Forms.RadioButton #create the radio button
$RadioButton1.Location = '20,40'
$RadioButton1.size = '350,20'
$RadioButton1.Checked = $false #is checked by default
$RadioButton1.Text = "Dev" #labeling the radio button
$RadioButton1.Checked($event)
#Declare option buttons to allow user to select Dev OR System Test
$RadioButton2 = New-Object System.Windows.Forms.RadioButton #create the radio button
$RadioButton2.Location = '20,70'
$RadioButton2.size = '350,20'
#$RadioButton2.Location = new-object System.Drawing.Point(10,40) #location of the radio button(px) in relation to the group box's edges (length, height)
#$RadioButton2.size = New-Object System.Drawing.Size(80,20) #the size in px of the radio button (length, height)
$RadioButton2.Checked = $false #is checked by default
$RadioButton2.Text = "System test" #labeling the radio button
$RadioButton2.Checked($event)
$event={
if ($RadioButton1.Checked){
[System.Windows.Forms.MessageBox]::Show("You select Dev")}
elseif ($RadioButton2.Checked){
[System.Windows.Forms.MessageBox]::Show("You Selected System Test")}
}
#Create List Box
$ListBox1 = New-Object System.Windows.Forms.ListBox
$ListBox1.Location = New-Object System.Drawing.Size(20,200)
$ListBox1.Size = New-Object System.Drawing.Size(260,20)
$ListBox1.Height = 80
#POPULATE WHAT IT WILL HOLD
$Servers = get-content -path "xxxx.csv"
write-host $Servers
ForEach ($Server in $Servers){
#$NL = "`r`n"
[void] $ListBox1.Items.Add($Server)
}
#Create the Form
# Add all the GroupBox controls on one line
$Form.Controls.Add($ListBox1)
$form.Controls.AddRange(#($MyGroupBox))
$MyGroupBox.Controls.AddRange(#($Radiobutton1,$RadioButton2))
$Form.Add_Shown({$Form.Activate()})
$dialogResult =$Form.ShowDialog()
}
SQLDoTasks
First, you have to declare the $event scriptblock before you add the event handler. So I would define both buttons, then the scriptblock and then add the handlers. Also, you probably should use the Add_Click callback:
#....
$RadioButton2 = New-Object System.Windows.Forms.RadioButton #create the radio button
$RadioButton2.Location = '20,70'
$RadioButton2.size = '350,20'
#$RadioButton2.Location = new-object System.Drawing.Point(10,40) #location of the radio button(px) in relation to the group box's edges (length, height)
#$RadioButton2.size = New-Object System.Drawing.Size(80,20) #the size in px of the radio button (length, height)
$RadioButton2.Checked = $false #is checked by default
$RadioButton2.Text = "System test" #labeling the radio button
$event={
if ($RadioButton1.Checked){
[System.Windows.Forms.MessageBox]::Show("You select Dev")}
elseif ($RadioButton2.Checked){
[System.Windows.Forms.MessageBox]::Show("You Selected System Test")}
}
$RadioButton1.Add_Click($event)
$RadioButton2.Add_Click($event)