Im working on a project in Powershell the uses WPF controls.
I have a datagridview where only one full row can be selected. There is also a contextmenustrip that is working fine in the datagridview as well.
My problem is that I would like a right-click mouse event to select the row on which it was clicked and display the contextmenustrip. so there is no question for the user what they clicked. Currently, the selected row doesnt change on right click.
I've found many examples, but could use some guidance on converting them for use in powershell.
Once i get this down, i want to assign actions to each of the contextmenustrip selections Thanks!
The code in the linked answer, can be translated to PowerShell like as follows.
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
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
}