How can I correctly handle events of Windows Forms controls in PowerShell and use Sender and EventArgs?
What's the equivalent of following C# code in PowerShell?
button.MouseClick += (sender, e) => {
MessageBox.Show($"{((Control)sender).Name} \n {e.Location}");
};
The following example shows an event handler for a Button control's Click event. The first parameter, sender , provides a reference to the object that raised the event. The second parameter, e , in the example above, passes an object specific to the event that is being handled.
To correctly handle events of a Windows Forms control in PowerShell and take advantage of Sender and EventArgs you can use either of the following options:
sender and e parameters for script clock$this and $_ VariablesDefine sender and e parameters for script block
Like lambda event handlers in C#, you can define param($sender,$e) for the script block:
$button.Add_MouseClick({param($sender,$e)
[System.Windows.Forms.MessageBox]::Show(" $($sender.Name) `n $($e.Location)")
})
Use $this and $_ Variables
$this is the sender of the event and $_ is the event args:
$button.Add_MouseClick({
[System.Windows.Forms.MessageBox]::Show(" $($this.Name) `n $($_.Location)")
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With