问题描述
因此,我尝试根据满足特定条件的字符串数量在另一张图像上创建动态数量的图像对象。到现在为止还挺好。似乎无法使用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)
}
}