简体   繁体   中英

Right Click to select a row in datagridview control in powershell

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.

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(eX, eY); //...

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM