31

I am trying to show a popup menu on my treeview when users right click - allowing them to choose context sensitive actions to apply against the selected node.

At the moment the user has to left click node and then right click to choose.

Is it possible to make a right click on a node select that node - and if so what is the best method to do this.

Martin
  • 39,569
  • 20
  • 99
  • 130

3 Answers3

58

Both left and right clicks fire a click event and cause the selection to change. However, in certain circumstances (that I haven't yet bothered to trace down) the selection will change from the node that was right clicked to the originally selected node.

In order to make sure that the right click changes the selection, you can forcibly change the selected node by using the MouseDown event:

treeView.MouseDown += (sender, args) =>
    treeView.SelectedNode = treeView.GetNodeAt(args.X, args.Y);

A little better, as one of the other posters pointed out, is to use the NodeMouseClick event:

treeView.NodeMouseClick += (sender, args) => treeView.SelectedNode = args.Node;
Kaleb Pederson
  • 45,767
  • 19
  • 102
  • 147
  • 4
    I agree. Simply adding this code to my Form's constructor did the trick for me. Thank you. – Kevin Hicks Sep 14 '12 at 04:42
  • One issue I had with the NodeMouseClick approach is that it changes the selected node at the end of the NodeMouseClick event. So, for my purposes, I wanted the selected node to change before any context menu was displayed. In order to do that, I had to use the MouseDown approach. – cigarman Mar 01 '14 at 00:08
  • Yes Coleman. I add validation: if (e.Button == MouseButtons.Right) ... (less charge) – Sith2021 Apr 14 '14 at 02:09
16

yes. Here is processing for NodeMouseClick event:

private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
{
      treeView1.SelectedNode = e.Node;
}
Majid
  • 13,853
  • 15
  • 77
  • 113
Sasha Reminnyi
  • 3,442
  • 2
  • 23
  • 27
5

Drag a context menu strip onto the form then:

 private void treeView1_MouseDown(object sender, MouseEventArgs e)
 {
   if (e.Button == MouseButtons.Right)
   {
       // Display context menu for eg:
       ContextMenu1.Show();
   }
}
nik0lai
  • 2,585
  • 23
  • 37