powershell - 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
变量。
这将如何正确完成?
解决方案
经过一番认真的阅读,我明白了。
需要添加名称$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'
})
但是我不知道这是否应该这样做。如果看起来不同,请发布您的解决方案。
推荐阅读
- python - 了解 Python OpenCV (cv2) 中的 HoughCircles
- python - 在 python 中读取上标 (NG²) 和 latin-1 的编码格式是什么?
- sql - Sql 查询没有返回想要的结果
- php - PHP 无法从邮件程序中获取返回值
- c - 使用 C 打印学生综合成绩的平均值
- javascript - 使用 queryselector 添加点击处理程序不起作用
- r - R 官员 - 将数据框嵌套到分组列表中并将表导出到带有组标题的 Word
- android - Azure 媒体服务中的 MPEG-DASH 错误
- python - 将数据从一个数据帧复制到另一个数据帧
- go - 如何在 sarama 中获得多个订阅