首页 > 解决方案 > Powershell 多个动态按钮

问题描述

我构建了一个动态 Powershell GUI,但我的按钮无法正常工作。

我创建了一个函数来添加 texboxes 和按钮。但是,此时它们没有正确对应。因为我不确定如何将其绑定add_click到特定的文本框。

这是示例代码:

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

$Form = New-Object System.Windows.Forms.Form    
$Form.Size = New-Object System.Drawing.Size(300,300)  

$ButtonAdd = New-Object System.Windows.Forms.Button
$ButtonAdd.Location = New-Object System.Drawing.Point(20,20)
$ButtonAdd.Size = New-Object System.Drawing.Size(50,30)
$ButtonAdd.Text = 'Add'
$Form.Controls.Add($ButtonAdd)

$global:Counter = 0
$global:ButtonPosY = 20
$global:DefaultTextValue = ""

$ButtonAdd.Add_Click{Add-Fields}

Function Create-Button {
    param ( $ButtonPosY, $TextBoxPosY)

    $TextBoxField = New-Object System.Windows.Forms.TextBox
    $TextBoxField.Location = New-Object System.Drawing.Point(181,$TextBoxPosY)
    $TextBoxField.Size = New-Object System.Drawing.Size(50,30)
    $TextBoxField.Text = $global:DefaultTextValue
    New-Variable -name TextBoxField$global:Counter -Value $TextBoxField -Scope Global -Force
    $Form.controls.Add($((Get-Variable -name TextBoxField$global:Counter).value))

    $ButtonClick = New-Object System.Windows.Forms.Button
    $ButtonClick.Location = New-Object System.Drawing.Point(100,$global:ButtonPosY)
    $ButtonClick.Size = New-Object System.Drawing.Size(50,30)
    $ButtonClick.Text = 'Click'
    New-Variable -name ButtonClick$global:Counter -Value $ButtonClick -Scope Global -Force
    $Form.controls.Add($((Get-Variable -name ButtonClick$global:Counter).value))

    $ButtonClick.Add_Click({
        $((Get-Variable -name TextBoxField$global:Counter -Scope Global).value).Text = 'hello'
    })
}

Function Add-Fields {

    $global:Counter = $global:Counter + 1
    $global:ButtonPosY = $global:ButtonPosY + 40

    Create-Button -TextBoxPosY $global:ButtonPosY -ButtonPosY $global:ButtonPosY

}

Create-Button -TextBoxPosY 21 -ButtonPosY 20

$Form.ShowDialog()

如果在click添加新输入后每次按下按钮,一切正常。但是,如果首先添加多个输入字段,然后click按下按钮,则代码会中断。

问题在这里:

    $ButtonClick.Add_Click({...})

我不知道如何将计数器(在我的情况下$global:Counter)添加到$ButtonClick变量中,如$ButtonClick0, $ButtonClick1, ... etc. 所以现在当我通过调用函数添加更多按钮时,输入将始终应用于最后添加的文本框,因为add_click它没有链接到单个$ButtonClick0变量。

这将如何正确完成?

标签: powershell

解决方案


经过一番认真的阅读,我明白了。

需要添加名称$ButtonClick

$ButtonClick.Name = $global:Counter

Add_Click事件应如下所示:

$ButtonClick.Add_Click({
    [System.Object]$Sender = $args[0]
    $((Get-Variable -name ('TextBoxField' + [int]$Sender.Name)).value).Text = 'hello'
})

但是我不知道这是否应该这样做。如果看起来不同,请发布您的解决方案。


推荐阅读