winforms - 获取 parent 姓名

标签 winforms powershell event-handling

用什么方法或变量可以找到本例中父对象的名称?也就是说,当鼠标悬停在第一个按钮上时,获取名称 $GetParentName = "Button01",第二个 $GetParentName = "Button02",第三个 $GetParentName = “Button03”。 $GetParentName 为 [string]

如果不是使用变量 $GetParentName 来应用 $This,则变量 $This 允许您获取对象的值,但没有获取对象的名称。但如何获取对象的名称呢?谢谢

已编辑:未使用 $This.Name。

$A = @{

    Main = [System.Windows.Forms.Form] @{ StartPosition = 'CenterParent' }

    Button01 = [System.Windows.Forms.Button] @{ Top = 0 }
    Button02 = [System.Windows.Forms.Button] @{ Top = 30 }
    Button03 = [System.Windows.Forms.Button] @{ Top = 60 }
}

$Script = { Write-host $GetParentName }

1..3 | % {

    $A["Button0$_"].Add_MouseEnter($Script)

    $A.Main.Controls.Add($A["Button0$_"])
}

[void]$A.Main.ShowDialog()

最佳答案

如果您想在 MouseEnter 脚本中获取按钮控件的名称,则需要设置按钮控件的 .Name 属性:

Add-Type -AssemblyName System.Windows.Forms

$A = @{

    Main = [System.Windows.Forms.Form] @{ StartPosition = 'CenterParent' }

    Button01 = [System.Windows.Forms.Button] @{ Top = 0  ; Name = 'Button01'}
    Button02 = [System.Windows.Forms.Button] @{ Top = 30 ; Name = 'Button02'}
    Button03 = [System.Windows.Forms.Button] @{ Top = 60 ; Name = 'Button03'}
}

$Script = { Write-host $this.Name }

1..3 | ForEach-Object {

    $A["Button0$_"].Add_MouseEnter($Script)

    $A.Main.Controls.Add($A["Button0$_"])
}

[void]$A.Main.ShowDialog()

$A.Main.Dispose()

<小时/> 编辑

ForEach-Object 循环内创建和命名按钮可以节省您为每个按钮键入名称的时间:

Add-Type -AssemblyName System.Windows.Forms

$A = @{
    Main = [System.Windows.Forms.Form] @{ StartPosition = 'CenterParent' }
}

$Script = { Write-host $this.Name }

1..3 | ForEach-Object {
    $A["Button0$_"] = [System.Windows.Forms.Button] @{ Top = ($_ -1) * 30 ; Name = "Button0$_"}
    $A["Button0$_"].Add_MouseEnter($Script)

    $A.Main.Controls.Add($A["Button0$_"])
}

[void]$A.Main.ShowDialog()

$A.Main.Dispose()

关于winforms - 获取 parent 姓名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60226779/

相关文章:

powershell - 如何在类方法调用内联中嵌套函数调用

c++ - 回调到 COM 对象的 powershell 函数

angularjs - 模式对话框关闭时调用函数的数据属性

c# - 如何在 C# 中查找通用控件的标记

powershell - 为什么Powershell的 "return"关键字会导致类型错误?

powershell - PowerShell 中 Power BI Rest API 的错误处理

jquery - 通过拖动分隔线处理程序来调整元素大小

c# - 如果不先删除监听器,重新分配数据源会导致内存泄漏吗?

C# 列表框 ObservableCollection<T>

c# - FolderBrowserDialog 的替代品