<# MIT License Copyright (c) 2020 Benjamin Turmo Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. .NOTES =========================================================================== FileName: WinFormsCreator.ps1 Author: PSWinFormsCreator.com Admin (Benjamin Turmo) Created On: 1/15/2020 Last Updated: 12/14/2020 Version: v2.0.0.0 =========================================================================== .DESCRIPTION Use this script in the creation of other WinForms PowerShell scripts. Has the ability to Save/Open a project, modify most properties of any control, and generate a script file. The resulting script file initializes the Form in a STA runspace. .DEPENDENCIES PowerShell 4.0 .Net .UPDATES 1.0.0.1 - 06/13/2020 Added MIT License 1.0.1.0 - 06/20/2020 Added DataGridView Corrected issue where able to add controls directly to TabControl instead of TabPage 1.0.2.0 - 7/10/2020 Added TabPage for TabControl Added SplitterPanel for SplitContainer Fixed Size property being saved when Dock set to Fill or AutoSize to true Updated UI: Moved Toolbox/Events to SplitterPanel in a TabControl on Mainform. All controls now in SplitContainers to allow for finer UI customization and to allow for maximization of the Mainform. There are some changes to the UI that were made in preparation for updating to a MDI child form and to allow for other future development. 2.0.0.0 - 12/14/2020 Complete UI Overhaul to make more traditional and allow for future feature additions/enhancement Property values being saved in the form XML is now dependent on the property reflector of the PropertyGrid GridItem. Does still keep track of every change because of issues with reflectors (see Known Issues). Unsupported: Multi-threading Drag/Drop addition of controls Adding Mouse Events to WebBrowser control Previous pre-2.0.0.0 version save files will not open properly in 2.0.0.0+ If the Items Element is removed from Data it should load properly Known Issues: DataGridView - All CellStyle Properties will save, but get exception when setting on Open ListView - ListViewItem and ListViewGroup Properties will not save TreeView - Nodes property will not save TextBox - AutoCompleteCustomSource Property will not save Form - Unable to change IsMDIContainer to True and issue Maximizing Window State Certain property reflectors will show that a value has been changed when it has not. This issue affects the following properties on all controls: UseCompatibleTextRendering, TabIndex, and TabStop. In order for these properties to be saved to form XML they need to be manually changed in the PropertyGrid. After this point, the property value will always be generated in the form XML for that specific control. Images/Icons do not save 2.0.1.0 - 12/26/2020 Corrected issue after resizing of Form in design after resize to refresh parent Form Fixed issue with Size property on Forms and Textboxes to save correctly #> # ScriptBlock to Execute in STA Runspace $sbGUI = { param($BaseDir) #region Functions function Update-ErrorLog { param( [System.Management.Automation.ErrorRecord]$ErrorRecord, [string]$Message, [switch]$Promote ) if ( $Message -ne '' ) {[void][System.Windows.Forms.MessageBox]::Show("$($Message)`r`n`r`nCheck '$($BaseDir)\exceptions.txt' for details.",'Exception Occurred')} $date = Get-Date -Format 'yyyyMMdd HH:mm:ss' $ErrorRecord | Out-File "$($BaseDir)\tmpError.txt" Add-Content -Path "$($BaseDir)\exceptions.txt" -Value "$($date): $($(Get-Content "$($BaseDir)\tmpError.txt") -replace "\s+"," ")" Remove-Item -Path "$($BaseDir)\tmpError.txt" if ( $Promote ) {throw $ErrorRecord} } function ConvertFrom-WinFormsXML { param( [Parameter(Mandatory=$true)]$Xml, [string]$Reference, $ParentControl, [switch]$Suppress ) try { if ( $Xml.GetType().Name -eq 'String' ) {$Xml = ([xml]$Xml).ChildNodes} if ( $Xml.ToString() -ne 'SplitterPanel' ) {$newControl = New-Object System.Windows.Forms.$($Xml.ToString())} if ( $ParentControl ) { if ( $Xml.ToString() -match "^ToolStrip" ) { if ( $ParentControl.GetType().Name -match "^ToolStrip" ) {[void]$ParentControl.DropDownItems.Add($newControl)} else {[void]$ParentControl.Items.Add($newControl)} } elseif ( $Xml.ToString() -eq 'ContextMenuStrip' ) {$ParentControl.ContextMenuStrip = $newControl} elseif ( $Xml.ToString() -eq 'SplitterPanel' ) {$newControl = $ParentControl.$($Xml.Name.Split('_')[-1])} else {$ParentControl.Controls.Add($newControl)} } $Xml.Attributes | ForEach-Object { $attrib = $_ $attribName = $_.ToString() if ( $Script:specialProps.Array -contains $attribName ) { if ( $attribName -eq 'Items' ) { $($_.Value -replace "\|\*BreakPT\*\|","`n").Split("`n") | ForEach-Object{[void]$newControl.Items.Add($_)} } else { # Other than Items only BoldedDate properties on MonthCalendar control $methodName = "Add$($attribName)" -replace "s$" $($_.Value -replace "\|\*BreakPT\*\|","`n").Split("`n") | ForEach-Object{$newControl.$attribName.$methodName($_)} } } else { switch ($attribName) { FlatAppearance { $attrib.Value.Split('|') | ForEach-Object {$newControl.FlatAppearance.$($_.Split('=')[0]) = $_.Split('=')[1]} } default { if ( $null -ne $newControl.$attribName ) { if ( $newControl.$attribName.GetType().Name -eq 'Boolean' ) { if ( $attrib.Value -eq 'True' ) {$value = $true} else {$value = $false} } else {$value = $attrib.Value} } else {$value = $attrib.Value} $newControl.$attribName = $value } } } if (( $attrib.ToString() -eq 'Name' ) -and ( $Reference -ne '' )) { try {$refHashTable = Get-Variable -Name $Reference -Scope Script -ErrorAction Stop} catch { New-Variable -Name $Reference -Scope Script -Value @{} | Out-Null $refHashTable = Get-Variable -Name $Reference -Scope Script -ErrorAction SilentlyContinue } $refHashTable.Value.Add($attrib.Value,$newControl) } } if ( $Xml.ChildNodes ) {$Xml.ChildNodes | ForEach-Object {ConvertFrom-WinformsXML -Xml $_ -ParentControl $newControl -Reference $Reference -Suppress}} if ( $Suppress -eq $false ) {return $newControl} } catch {Update-ErrorLog -ErrorRecord $_ -Message "Exception encountered adding $($Xml.ToString()) to $($ParentControl.Name)"} } function Convert-XmlToTreeView { param( [System.Xml.XmlLinkedNode]$Xml, $TreeObject, [switch]$IncrementName ) try { $controlType = $Xml.ToString() $controlName = "$($Xml.Name)" if ( $IncrementName ) { $objRef = Get-RootNodeObjRef -TreeNode $Script:refs['TreeView'].SelectedNode $returnObj = [pscustomobject]@{OldName=$controlName;NewName=""} $loop = 1 while ( $objRef.Objects.Keys -contains $controlName ) { if ( $controlName.Contains('_') ) { $afterLastUnderscoreText = $controlName -replace "$($controlName.Substring(0,($controlName.LastIndexOf('_') + 1)))" if ( $($afterLastUnderscoreText -replace "\D").Length -eq $afterLastUnderscoreText.Length ) { $controlName = $controlName -replace "_$($afterLastUnderscoreText)$","_$([int]$afterLastUnderscoreText + 1)" } else {$controlName = $controlName + '_1'} } else {$controlName = $controlName + '_1' } # Make sure does not cause infinite loop if ( $loop -eq 1000 ) {throw "Unable to determine incremented control name."} $loop++ } $returnObj.NewName = $controlName $returnObj } if ( $controlType -ne 'SplitterPanel' ) {Add-TreeNode -TreeObject $TreeObject -ControlType $controlType -ControlName $controlName} $objRef = Get-RootNodeObjRef -TreeNode $Script:refs['TreeView'].SelectedNode $newControl = $objRef.Objects[$controlName] $Xml.Attributes.GetEnumerator().ForEach({ if ( $_.ToString() -ne 'Name' ) { if ( $null -eq $objRef.Changes[$controlName] ) {$objRef.Changes[$controlName] = @{}} if ( $null -ne $($newControl.$($_.ToString())) ) { if ( $($newControl.$($_.ToString())).GetType().Name -eq 'Boolean' ) { if ( $_.Value -eq 'True' ) {$value = $true} else {$value = $false} } else {$value = $_.Value} } else {$value = $_.Value} try {$newControl.$($_.ToString()) = $value} catch {if ( $_.Exception.Message -notmatch 'MDI container forms must be top-level' ) {throw $_}} $objRef.Changes[$controlName][$_.ToString()] = $_.Value } }) if ( $Xml.ChildNodes.Count -gt 0 ) { if ( $IncrementName ) {$Xml.ChildNodes.ForEach({Convert-XmlToTreeView -Xml $_ -TreeObject $objRef.TreeNodes[$controlName] -IncrementName})} else {$Xml.ChildNodes.ForEach({Convert-XmlToTreeView -Xml $_ -TreeObject $objRef.TreeNodes[$controlName]})} } } catch {Update-ErrorLog -ErrorRecord $_ -Message "Exception encountered adding '$($Xml.ToString()) - $($Xml.Name)' to Treeview."} } function Get-CustomControl { param( [Parameter(Mandatory=$true)][hashtable]$ControlInfo, [string]$Reference, [switch]$Suppress ) try { $refGuid = [guid]::NewGuid() $control = ConvertFrom-WinFormsXML -Xml "$($ControlInfo.XMLText)" -Reference $refGuid $refControl = Get-Variable -Name $refGuid -ValueOnly if ( $ControlInfo.Events ) {$ControlInfo.Events.ForEach({$refControl[$_.Name]."add_$($_.EventType)"($_.ScriptBlock)})} if ( $Reference -ne '' ) {New-Variable -Name $Reference -Scope Script -Value $refControl} Remove-Variable -Name refGuid -Scope Script if ( $Suppress -eq $false ) {return $control} } catch {Update-ErrorLog -ErrorRecord $_ -Message "Exception encountered getting custom control."} } function Get-UserInputFromForm { param([string]$SetText) try { $inputForm = Get-CustomControl -ControlInfo $Script:childFormInfo['NameInput'] if ( $inputForm ) { $inputForm.AcceptButton = $inputForm.Controls['StopDingOnEnter'] $inputForm.Controls['UserInput'].Text = $SetText [void]$inputForm.ShowDialog() $returnVal = [pscustomobject]@{ Result = $inputForm.DialogResult NewName = $inputForm.Controls['UserInput'].Text } return $returnVal } } catch { Update-ErrorLog -ErrorRecord $_ -Message "Exception encountered setting new control name." } finally { try {$inputForm.Dispose()} catch {if ( $_.Exception.Message -ne "You cannot call a method on a null-valued expression." ) {throw $_}} } } function Add-TreeNode { param( $TreeObject, [string]$ControlType, [string]$ControlName ) if ( $ControlName -eq '' ) { $userInput = Get-UserInputFromForm -SetText "$($Script:supportedControls.Where({$_.Name -eq $ControlType}).Prefix)_" if ( $userInput.Result -eq 'OK' ) {$ControlName = $userInput.NewName} } try { if ( $TreeObject.GetType().Name -eq 'TreeView' ) { if ( $ControlType -eq 'Form' ) { # Clear the Assigned Events ListBox $Script:refs['lst_AssignedEvents'].Items.Clear() $Script:refs['lst_AssignedEvents'].Items.Add('No Events') $Script:refs['lst_AssignedEvents'].Enabled = $false # Create the TreeNode $newTreeNode = $TreeObject.Nodes.Add($ControlName,"Form - $($ControlName)") # Create the Form $form = New-Object System.Windows.Forms.Form $form.Name = $ControlName $form.Location = New-Object System.Drawing.Point(0,0) $form.Add_FormClosing({ param($Sender,$e) $e.Cancel = $true }) $form.Add_Click({ if (( $Script:refs['PropertyGrid'].SelectedObject -ne $this ) -and ( $args[1].Button -eq 'Left' )) { $Script:refs['TreeView'].SelectedNode = $Script:refsFID.Form.TreeNodes[$this.Name] } }) $form.Add_ReSize({ if ( $Script:refs['PropertyGrid'].SelectedObject -ne $this ) {$Script:refs['TreeView'].SelectedNode = $Script:refsFID.Form.TreeNodes[$this.Name]} $Script:refs['PropertyGrid'].Refresh() $this.ParentForm.Refresh() }) $form.Add_LocationChanged({$this.ParentForm.Refresh()}) $form.Add_ReSizeEnd({ if ( $Script:refs['PropertyGrid'].SelectedObject -ne $this ) {$Script:refs['TreeView'].SelectedNode = $Script:refsFID.Form.TreeNodes[$this.Name]} $Script:refs['PropertyGrid'].Refresh() $this.ParentForm.Refresh() }) # Add the selected object control buttons $Script:sButtons = $null Remove-Variable -Name sButtons -Scope Script -ErrorAction SilentlyContinue ConvertFrom-WinFormsXML -ParentControl $form -Reference sButtons -Suppress -Xml '