Q:

Windows Forms Events in PowerShell - Sender and EventArgs in PowerShell

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}");
};

A:

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:

Define sender and e parameters for script clock
Use $this and $_ Variables

Define 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)")
})

