Getting the node the user right clicked on

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi

In a treeview How do I get the node that the user right clicked on. I need
to modify the contecxt menu based on the node
 
Hylton,

In .NET 2.0, you can call the HitTest method on the TreeView to get a
TreeViewHitTestInfo class instance which will have the node that the point
passed to the HitTest method points to (if there is one).

If not in .NET 2.0, you will have to call SendMessage through the
P/Invoke layer, passing the TV_HITTESTINFO message to get the location of
the the node at the specified coordinates.

Hope this helps.
 
Found another solution too.

private void treeView1_MouseDown(object sender,
System.Windows.Forms.MouseEventArgs e)
{
if(MouseButtons.Right)
{
TreeNode node = treeView1.GetNodeAt(e.X, e.Y);
....
}
}

Nicholas Paldino said:
Hylton,

In .NET 2.0, you can call the HitTest method on the TreeView to get a
TreeViewHitTestInfo class instance which will have the node that the point
passed to the HitTest method points to (if there is one).

If not in .NET 2.0, you will have to call SendMessage through the
P/Invoke layer, passing the TV_HITTESTINFO message to get the location of
the the node at the specified coordinates.

Hope this helps.


--
- Nicholas Paldino [.NET/C# MVP]
- (e-mail address removed)

Hylton said:
Hi

In a treeview How do I get the node that the user right clicked on. I need
to modify the contecxt menu based on the node
 
declare a global variable holding the last selected node.

private TreeNode currentNode;

handle the AfterSelect event of the treeview.



private void treeView1_AfterSelect(object sender,
System.Windows.Forms.TreeViewEventArgs e)

{

currentNode = e.Node;

}



handle the doubleclick and keydown events to capture the enter key.



private void treeView1_DoubleClick(object sender, System.EventArgs e)

{

MessageBox.Show(currentNode.Text);

}



private void treeView1_KeyDown(object sender,
System.Windows.Forms.KeyEventArgs e)

{

if(e.KeyCode == Keys.Enter)

{

MessageBox.Show(currentNode.Text);

}

}



note that doubleclick behaviour will be not desired if the mouse is not
clicked a node.
 
Back
Top