The code in the linked answer, can be translated to PowerShell like as follows.
Event handler registration
this.MyDataGridView.MouseDown += new System.Windows.Forms.MouseEventHandler(this.MyDataGridView_MouseDown);
this.DeleteRow.Click += new System.EventHandler(this.DeleteRow_Click);
PowerShell doesn't support +=
for event handler registration, but you have two other options. Either call the specially named methods that the C# ultimately converts +=
to - they will all have the form add_<EventName>
:
$dataGridView = [System.Windows.Forms.DataGridView]::new()
# ...
$dataGridView.add_MouseDown($dgvMouseHandler)
Alternatively, use the Register-ObjectEvent
cmdlet to let PowerShell handle the registration for you:
Register-ObjectEvent $dataGridView -EventName MouseDown -Action $dgvMouseHandler
Event arguments
private void MyDataGridView_MouseDown(object sender, MouseEventArgs e) {
if(e.Button == MouseButtons.Right)
{
var hti = MyDataGridView.HitTest(e.X, e.Y);
// ...
In order to consume the event handler arguments you can either declare the parameters defined by the handler delegate in the script block:
$dgvMouseHandler = {
param($sender,[System.Windows.Forms.MouseEventArgs]$e)
# now you can dereference `$e.X` like in the C# example
}
Or take advantage of the $EventArgs
automatic variable:
$dgvMouseHandler = {
# `$EventArgs.X` will also do
}