用什么方法或变量可以找到本例中父对象的名称?也就是说,当鼠标悬停在第一个按钮上时,获取名称 $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/