首页 > 解决方案 > foreach 中的对象 $Button / 如何引用它来改变颜色

问题描述

我正在使用 foreach 构建 GUI,现在......可以做 16 个按钮,但试图自动化构建一点:

1,2,3,4 | foreach { $Button...}

所有这一切都有效,我得到了 16 个具有正确偏移的按钮,但是当决定在按钮中使用作业、后台作业 ping、睡眠、ping 时卡住了一点 - 如果无法 ping 作业结束,此时我希望它更改按钮的颜色

由于所有按钮都是“$Button”,

foreach 可以在最后生成具有不同数字的 $button 吗?即 $Button1、$Button2... 等?试过 $Button$_ 但这没有用

或者关于如何引用按钮的任何想法,以便根据完成的工作可以改变该按钮的颜色?

干杯

@Wasif_Hasan 这不起作用

$i=120
1..4 | Foreach {Set-Variable -Name "Button$($_)" -Value "Value"
$i=$i+70
$Button = New-Object System.Windows.Forms.Button
$Button.Location = New-Object System.Drawing.Point(150,$i)
$Button.Size = New-Object System.Drawing.Size(75,23)
$Button.Text = 'Cancel'+$_
$Button.DialogResult = [System.Windows.Forms.DialogResult]::Cancel
$form.CancelButton = $Button
$form.Controls.Add($Button)
}
$Button3.Text = 'ok'+$_

错误:

The property 'Text' cannot be found on this object. Verify that the property exists and can be set.

可以保存为 .PS1 的代码以检查...

Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing

$form = New-Object System.Windows.Forms.Form
$form.Text = 'Select a Computer'
$form.Size = New-Object System.Drawing.Size(300,400)
$form.StartPosition = 'CenterScreen'

$i=10
1..4 | Foreach {Set-Variable -Name "Button$($_)" -Value "Value"
$i=$i+50
$Button = New-Object System.Windows.Forms.Button
$Button.Location = New-Object System.Drawing.Point(150,$i)
$Button.Size = New-Object System.Drawing.Size(75,23)
$Button.Text = "Number"+$_
$form.Controls.Add($Button)
}
$Button3.Text = "Test"
$result = $form.ShowDialog()

错误:

The property 'Text' cannot be found on this object. Verify that the property 
exists and can be set.
At line:19 char:1
+ $Button3.Text = "Test"
+ ~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : PropertyAssignmentException

解决方案,谢谢 Wasif_Hasan!

Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing

$form = New-Object System.Windows.Forms.Form
$form.Text = 'Select a Computer'
$form.Size = New-Object System.Drawing.Size(300,400)
$form.StartPosition = 'CenterScreen'
$Button=1,2,3,4
$i=10

$k=1
1,2,3,4 | Foreach {
$i=$i+50


    New-Variable "Button$_" -Value $(new-object System.Windows.Forms.Button -Property @{
        Name = 'Dvar'
        Location = New-Object System.Drawing.Size(10,$i)
        Size = New-Object System.Drawing.Size(75,23)
        Text = $_
    })

    $form.Controls.Add($(Get-Variable "Button$_" -ValueOnly))


$k=$k++
}
$Button2.Text="Hello"
$result = $form.ShowDialog()
$k=5
Remove-Variable Button*
$form.ActiveControl.Text

结果:1 你好 2 3

标签: powershell

解决方案


是的,设置它们使用这个:

1..4 | Foreach {Set-Variable -Name "Button$($_)" -Value "Value"}

您还可以获得以下值:

1..4 | Foreach {(Get-Variable -Name "Button$($_)").Value}

所有将像 $Button1、$Button2 等创建。


推荐阅读