创建动态分配数量的 PictureBoxes

Creating dynamically asigned amount of PictureBoxes

因此,我尝试根据满足特定条件的字符串数量,在另一张图片上创建动态数量的图像对象。到目前为止,一切都很好。看来我无法使用 cmdlet New-Variable 创建动态数量的 Windows.Forms.PictureBox 对象。如果有人知道如何创建这些盒子,我会很高兴

我知道 powershell 可能不是解决此问题的最佳解决方案,但目前是我唯一能做到的。

$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()

不要使用单个变量,如果需要跟踪它们,请改用列表:

$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)
    }
}