Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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}");
};
like image 527
Reza Aghaei Avatar asked Jul 02 '18 06:07

Reza Aghaei


People also ask

Which of the following is the second parameter of event handler method for click event?

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.


1 Answers

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)")
})
like image 180
Reza Aghaei Avatar answered Sep 23 '22 14:09

Reza Aghaei