Find node clicked under context menu

Sam picture Sam · Aug 5, 2008 · Viewed 55.7k times · Source

How can I find out which node in a tree list the context menu has been activated? For instance right-clicking a node and selecting an option from the menu.

I can't use the TreeViews' SelectedNode property because the node is only been right-clicked and not selected.

Answer

Jonesinator picture Jonesinator · Aug 5, 2008

You can add a mouse click event to the TreeView, then select the correct node using GetNodeAt given the mouse coordinates provided by the MouseEventArgs.

void treeView1MouseUp(object sender, MouseEventArgs e)
{
    if(e.Button == MouseButtons.Right)
    {
        // Select the clicked node
        treeView1.SelectedNode = treeView1.GetNodeAt(e.X, e.Y);

        if(treeView1.SelectedNode != null)
        {
            myContextMenuStrip.Show(treeView1, e.Location);
        }
    }
}