通过哈希表创建PowerShell按钮时动态变量问题求助
问题:通过哈希表动态创建Windows Forms按钮时执行出错
我希望通过哈希表创建多个Windows Forms按钮,但动态变量的创建与访问无法正常工作。以下是我的脚本:
$ButtonList = @{ 'NumPad1' = "Enter" 'NumPad2' = "ESC" } function WriteButtonName ($sBName){ Write-Host $sBName } $x_pos= 35 $form = New-Object System.Windows.Forms.Form foreach($b in $ButtonList.GetEnumerator()){ $Name = $($b.Name) $Value = $($b.Value) New-Variable -Name $Name -Value New-Object System.Windows.Forms.Button #$(get-variable -Name $Name) = New-Object System.Windows.Forms.Button (get-variable -Name $Name).Location = New-Object System.Drawing.Size($x_pos,35) (get-variable -Name $Name).Size = New-Object System.Drawing.Size(120,23) (get-variable -Name $Name).Text = $Value (get-variable -Name $Name).Add_Click({WriteButtonName -sBName $Name }) $x_pos += 130 }
运行时出现错误:
New-Variable - No position parameter was found that accepts the System.Windows.Forms.Button argument.
请问我哪里出错了?感谢解答。
问题分析与解决
1. 直接触发错误的语法问题
你在New-Variable的-Value参数后直接写了New-Object System.Windows.Forms.Button,PowerShell会把这段代码当成未执行的命令文本而非按钮对象实例。正确写法是用括号包裹New-Object命令,让它先执行生成对象再赋值:
New-Variable -Name $Name -Value (New-Object System.Windows.Forms.Button)
2. 隐藏的事件绑定陷阱
即使修复上述错误,点击按钮时所有按钮都会输出最后一个$Name的值(如NumPad2)。这是因为PowerShell脚本块会延迟绑定变量,直到事件触发时才读取$Name的当前值,而循环结束后$Name已经是最后一次循环的内容。
3. 更优的实现方案:用哈希表管理按钮
动态变量不利于后续维护,直接用哈希表存储所有按钮实例会更清晰。同时补上你遗漏的「将按钮添加到窗体」的关键步骤,否则按钮不会显示。
修正后的完整代码
$ButtonList = @{ 'NumPad1' = "Enter" 'NumPad2' = "ESC" } function WriteButtonName ($sBName){ Write-Host $sBName } $x_pos= 35 $form = New-Object System.Windows.Forms.Form # 用哈希表存储所有按钮,方便后续管理 $Buttons = @{} foreach($b in $ButtonList.GetEnumerator()){ $Name = $b.Name $Value = $b.Value # 创建按钮并存入哈希表 $button = New-Object System.Windows.Forms.Button $Buttons[$Name] = $button # 设置按钮属性 $button.Location = New-Object System.Drawing.Size($x_pos,35) $button.Size = New-Object System.Drawing.Size(120,23) $button.Text = $Value $button.Name = $Name # 绑定点击事件,使用按钮自身Name属性避免延迟绑定问题 $button.Add_Click({ WriteButtonName -sBName $this.Name }) # 将按钮添加到窗体 $form.Controls.Add($button) $x_pos += 130 } # 显示窗体 $form.ShowDialog() | Out-Null
内容的提问来源于stack exchange,提问作者TheRob87
相关产品推荐
相关产品推荐

