Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell: Duplicate windows forms with different properties

I am trying make copies of windows forms objects and change the properties of new objects. For example:

$List1 = New-Object System.Windows.Forms.ListBox
$List1.Location = New-Object System.Drawing.Size(10,10)
$List1.Size = New-Object System.Drawing.Size(280,310)

$List2 = $List1
$List2.Location = New-Object System.Drawing.Size(350,10)

The problem is that $List2 is a pointer of $List1. Whatever I change on $List2 always change the properties on $List1. Is there a solution for this?

$List1.Location

IsEmpty   X  Y
-------   -  -
  False 350 10



$List1.Location

IsEmpty   X  Y
-------   -  -
  False 350 10
like image 926
Vinkelman Avatar asked Aug 04 '26 14:08

Vinkelman


1 Answers

Whatever I change on $List2 always change the properties on $List1. Is there a solution for this?

Yes, the solution is to create a new instance of ListBox:

$List1 = New-Object System.Windows.Forms.ListBox
$List1.Location = New-Object System.Drawing.Size(10,10)
$List1.Size = New-Object System.Drawing.Size(280,310)

$List2 = New-Object System.Windows.Forms.ListBox
$List2.Size = $List1.Size
$List2.Location = New-Object System.Drawing.Size(350,10)

Notice that $List2.Size = $List1.Size is safe, because Size is a struct, and structs are copied on assignment


If you have many properties to reference, you could wrap the common property values in a hashtable to pass to New-Object -Property:

$ListBoxDefaultProperties = @{
    Location = New-Object System.Drawing.Size (10,10)
    Size = New-Object System.Drawing.Size (280,310)
    BackColor = 'Beige'
    DisplayMember = 'SomePropertyName'
    # etc...
}
$List1 = New-Object System.Windows.Forms.ListBox -Property $ListBoxDefaultProperties
$List2 = New-Object System.Windows.Forms.ListBox -Property $ListBoxDefaultProperties
$List3 = New-Object System.Windows.Forms.ListBox -Property $ListBoxDefaultProperties
like image 113
Mathias R. Jessen Avatar answered Aug 08 '26 18:08

Mathias R. Jessen