PowerShell动态创建WinForms按钮后,点击无法正确获取按钮唯一标识的问题求助
PowerShell动态创建WinForms按钮后,点击无法正确获取按钮唯一标识的问题求助
各位大佬好!我现在在写一段PowerShell脚本,想要实现的功能是:动态生成一批按钮(对应工单列表),用户点击其中任意一个按钮后,窗口直接关闭,并且能获取到被点击按钮的唯一标识(比如按钮文本或者我给它设的name属性),不需要单独的确定/取消按钮。
目前我的代码能正常创建按钮、调整窗口大小,但就是拿不到正确的点击结果——要么最后输出的$Button是空的,要么显示"cancelled"(我猜是因为Form.Close()的问题?),偶尔还只会返回第一个按钮的信息。我在点击事件里用Write-Host $this.text是能看到正确内容的,但到窗口关闭后就不对了,试了好多方法都没解决,实在摸不着头脑,麻烦大家帮我看看哪里出问题了?
我的代码如下:
#Add assemblies add-type -assemblyname System.Windows.Forms add-type -assemblyname System.Drawing #Define the form $Form = new-object System.Windows.Forms.Form $Form.text = 'Which ticket to work on?' $Tickets = "A","2","i" #Define each button for($i = 0; $i -lt $Tickets.count; $i++) { write-host "`$i = $i" $Button = new-object System.Windows.Forms.Button $Button.name = $i $Position = 25 + (55 * $i) $Button.location = new-object System.Drawing.Point(25,$Position) $Button.size = new-object System.Drawing.Size(525,50) $Button.text = $Tickets[$i] $Button.add_click({ $Button = $this.text $form.close() }.GetNewClosure()) $Form.Controls.Add($Button) } #Set form size, for contents $Height = 125 + (50 * ($Tickets.count)) $Form.Size = New-Object System.Drawing.Size(600,$Height) $Form.StartPosition = 'CenterScreen' $Form.Topmost = $true #display the form $Form.ShowDialog() #display the result "Button $Button was pressed"
我怀疑是变量作用域或者闭包的问题,但GetNewClosure()也加了,还是不对,到底哪里没考虑到呢?
内容来源于stack exchange
相关产品推荐
相关产品推荐

