在动态生成的控件上使用事件的变量

时间:2018-04-25 05:39:49

标签: forms powershell

我有一个函数TextBox,它创建一个Add-TextBox控件,并为它的事件处理程序分配一个块。

我面临的问题是该块可能是使用全局命名空间调用的,而Add-Type -AssemblyName System.Windows.Forms Function Add-Control() { Param ( [System.Windows.Forms.Form]$Form, [string]$ControlType, [System.Windows.Forms.Control]$AfterControl = $null, [int]$Padding = 0 ) $control = New-Object System.Windows.Forms.$ControlType $control.AutoSize = $true $x = 5 $y = 5 if ($AfterControl) { $y = $AfterControl.Location.Y + $AfterControl.Size.Height + $Padding } $control.Location = "5,$y" $form.Controls.Add($control) return $control } Function Add-TextBox() { Param ( [System.Windows.Forms.Form]$Form, [string]$Placeholder = "", [System.Windows.Forms.Control]$AfterControl = $null, [int]$Padding = 0 ) $control = Add-Control -Form $Form -ControlType "TextBox" -AfterControl $AfterControl -Padding $Padding $control.Add_GotFocus({ Write-Host "Placeholder is null: $($Placeholder -eq $null)" if ($this.Text -eq $Placeholder) { $this.ForeColor = "Black" $this.Text = "" } }) $control.Add_LostFocus({ if ($this.Text -eq "") { $this.ForeColor = "Darkgray" $this.Text = $Placeholder } }) return $control } $form = New-Object system.Windows.Forms.Form $textbox = Add-TextBox -Form $form -Placeholder "(XXXXXX, npr. 012345)" $form.ShowDialog() 函数内声明的变量是不可访问的。如何让它们可以访问?

修改:添加完整代码

{{1}}

1 个答案:

答案 0 :(得分:0)

似乎我可以在脚本块上使用.GetNewClosure()来捕获局部变量并保留它们。

Add-Type -AssemblyName System.Windows.Forms

Function Add-Control() {
    Param (
        [System.Windows.Forms.Form]$Form,
        [string]$ControlType,
        [System.Windows.Forms.Control]$AfterControl = $null,
        [int]$Padding = 0
    )

    $control = New-Object System.Windows.Forms.$ControlType

    $control.AutoSize = $true

    $x = 5
    $y = 5

    if ($AfterControl) {
        $y = $AfterControl.Location.Y + $AfterControl.Size.Height + $Padding
    }

    $control.Location = "5,$y"

    $form.Controls.Add($control)

    return $control
}

Function Add-TextBox() {
    Param (
        [System.Windows.Forms.Form]$Form,
        [string]$Placeholder = "",
        [System.Windows.Forms.Control]$AfterControl = $null,
        [int]$Padding = 0
    )

    $control = Add-Control -Form $Form -ControlType "TextBox" -AfterControl $AfterControl -Padding $Padding

    $control.Add_GotFocus({
        if ($this.Text -eq $Placeholder) {
            $this.ForeColor = "Black"
            $this.Text = ""
        }
    }.GetNewClosure()) # Here...

    $control.Add_LostFocus({
        if ($this.Text -eq "") {
            $this.ForeColor = "Darkgray"
            $this.Text = $Placeholder
        }
    }.GetNewClosure()) # And here.

    return $control
}


$form = New-Object system.Windows.Forms.Form

$textbox = Add-TextBox -Form $form -Placeholder "(XXXXXX, npr. 012345)"

$form.ShowDialog()