user4243325
user4243325

Reputation:

Load WinForm Object from CliXml PS

How can one save and load the properties of GUI objects from a CliXml file? Saving mwe is below, with failed attempt to load commented out. directly importing changes object type from System.Windows.Forms.Button to System.Management.Automation.PSObject. Attempts to loop over the saved properties failed.

Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.Application]::EnableVisualStyles()
Remove-Variable * -ErrorAction SilentlyContinue

$form = New-Object system.Windows.Forms.Form
$form.ClientSize = New-Object System.Drawing.Point(100,100)
$form.text = "Form"
$form.TopMost = $false
$form.FormBorderStyle = "FixedSingle"
$form.MaximizeBox = $false

$TestButton = New-Object system.Windows.Forms.Button
$TestButton.text = "Test"
$TestButton.width = 85
$TestButton.height = 30
$TestButton.location = New-Object System.Drawing.Point(0,0)
$TestButton.Font = New-Object System.Drawing.Font('Microsoft Sans Serif',12)
$TestButton.Enabled = $true

$path = "./vars/test.xml"
$TestButton | Export-CliXml $path

$TestButton.Enabled = $false

#$TestButton.GetType().FullName #For comp below
#$TestButton = Import-CliXml $path #Import the saved properties - intention is that this enables button again
#$TestButton.GetType() #The import changes the type. How to load saved properties and avoid this? 

$form.Controls.Add($TestButton)
[void]$form.ShowDialog()

Upvotes: 1

Views: 45

Answers (1)

iRon
iRon

Reputation: 23788

Why not "serialize" and save it as a PowerShell expression:

{
    New-Object system.Windows.Forms.Button -Property @{
        text = "Test"
        width = 85
        height = 30
        location = New-Object System.Drawing.Point(0,0)
        Font = New-Object System.Drawing.Font('Microsoft Sans Serif',12)
        Enabled = $true
    }
} | Out-File .\Vars\Test.ps1

Note: using the outer curly brackets will validate the expression, but you might also just use (here) quotes

And then load it using dot-sourcing:

$TestButton = . .\Vars\Test.ps1

Upvotes: 0

Related Questions