Search code examples
powershellpicturebox

Creating dynamically asigned amount of PictureBoxes


So I'm trying to create a dynamic amount of image objects onto another image depending on the amount of strings, which meet a certain condition. So far so good. It seems I can't create a dynamic amount of Windows.Forms.PictureBox Objects with the cmdlet New-Variable. If someone has a clue to how create these boxes, I'd be very happy

I'm aware that powershell is probably not the best solution for this but at the moment the only thing I'm barely capable of.

$path = (Get-Item "Insert Path here")
$path2 = (Get-Item "Insert Path here")

$img = [System.Drawing.Image]::Fromfile($path);
$img2 = [System.Drawing.Image]::FromFile($path2);

$test = Get-Content -Path "Insert Path here"

Foreach ($Line in $test){
    Write-Host $Line
    if ($Line -like "in 2*"){
        [int]$i++
        $Split1= $Line.Split(" ")
        $x=$Split1[4]
        $y=$Split1[5]
        
        #The Problem is in this line 
        New-Variable -Name "pictureBox$i" -Value (new-object Windows.Forms.PictureBox) 
        "$pictureBox$i".Width =  $img.Size.Width;
        "$pictureBox$i".Height =  $img.Size.Height;
        "$pictureBox$i".Location = New-object System.Drawing.Size($x,$y)
        "$pictureBox$i".Image = $img;
        $form.controls.add("$pictureBox$i")
    }
}

[void][reflection.assembly]::LoadWithPartialName("System.Windows.Forms")

[System.Windows.Forms.Application]::EnableVisualStyles();
$form = new-object Windows.Forms.Form
$form.Text = "Image Viewer"
$form.Width = 238;
$form.Height =  240;

$pictureBox20 = New-Object Windows.Forms.PictureBox
$pictureBox20.Width = $img2.Size.Width;
$pictureBox20.Height = $img2.Size.Height;

$pictureBox20.Image = $img2;
$form.Controls.Add($pictureBox20)
$form.Add_Shown( { $form.Activate() } )
$form.ShowDialog()

Solution

  • Don't use individual variables, use a list instead if you need to keep track of them:

    $pictureBoxes = New-Object 'System.Collections.Generic.List[Windows.Forms.PictureBox]'
    
    foreach ($Line in $test){
        Write-Host $Line
        if ($Line -like "in 2*"){
            $Split1 = $Line.Split(" ")
            $x = $Split1[4]
            $y = $Split1[5]
            
            #The Problem is in this line 
            $pictureBox = New-Object Windows.Forms.PictureBox
            $pictureBox.Width =  $img.Size.Width;
            $pictureBox.Height =  $img.Size.Height;
            $pictureBox.Location = New-object System.Drawing.Size($x,$y)
            $pictureBox.Image = $img;
            $form.Controls.Add($pictureBox)
    
            # Add to list for future reference
            $pictureBoxes.Add($pictureBox)
        }
    }