I have following code which is (almost) working as expected:
Add-Type -AssemblyName System.Windows.Forms
class MyForm : System.Windows.Forms.Form {
MyForm($mystuff) {
#Do-Stuff
$this.Add_Load( $this.MyForm_Load )
}
$MyForm_Load = {
$mlabel = [System.Windows.Forms.Label]::new()
$mlabel.Name = "label"
$mlabel.Text = "disabled"
$mbutton = [System.Windows.Forms.Button]::new()
$mbutton.Name = "button"
$mbutton.Location = [System.Drawing.Point]::new(100,100)
$mbutton.Add_Click( $this.mbutton_click )
$this.Controls.Add($mlabel)
$this.Controls.Add($mbutton)
# ----------------------------------------------
# Now $this.controls has something. We can now access it.
# ----------------------------------------------
if ($this.controls["label"].text -eq "enabled"){
$mbutton.text = "disable"
}else{
$mbutton.text = "enable"
}
}
$mbutton_click = {
if ($this.Parent.Controls["label"].Text -eq "enabled"){
$this.Parent.Controls["label"].Text = "disabled"
$this.Parent.Controls["button"].Text = "enable"
}
else{
$this.Parent.Controls["label"].Text = "enabled"
$this.Parent.Controls["button"].Text = "disable"
}
}
}
$foo = [MyForm]::new("test")
$foo.ShowDialog()
but when I replace following section:
$mbutton_click = {
if ($this.Parent.Controls["label"].Text -eq "enabled"){
$this.Parent.Controls["label"].Text = "disabled"
$this.Parent.Controls["button"].Text = "enable"
}
else{
$this.Parent.Controls["label"].Text = "enabled"
$this.Parent.Controls["button"].Text = "disable"
}
}
For this (missing Parent
):
$mbutton_click = {
if ($this.Controls["label"].Text -eq "enabled"){
$this.Controls["label"].Text = "disabled"
$this.Controls["button"].Text = "enable"
}
else{
$this.Controls["label"].Text = "enabled"
$this.Controls["button"].Text = "disable"
}
}
Then my script stops working and I see following error on console:
The property 'Text' cannot be found on this object. Verify that the property exists and can be set.
Why$MyForm_Load
works without Parent
but $mbutton_click
requires Parent
? Isn't both $MyForm_Load
and $mbutton_click
part of same object? How does Parent
works in System.Windows.Forms
?