PowerShell: Duplicate windows forms with different properties

Viewed 133

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
2 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

$List1 and $List2 reference the same object because you did $List1 = $List2.

You have to create 2 separate instances. You can set all common properties in a loop and then only change the properties that differ:

# 1. create two separate instances
$list1 = New-Object System.Windows.Forms.ListBox
$list2 = New-Object System.Windows.Forms.ListBox

# 2. set properties on both instances
foreach ($list in ($list1, $list2)) {
    $list.Location = New-Object System.Drawing.Size(10, 10)
    $list.Size = New-Object System.Drawing.Size(280, 310)
    # [...]
}

# 3. set all different properties on the 2nd instance only
$list2.Location = New-Object System.Drawing.Size(350, 10)
# [...]
Related