Search code examples
c#winformstreeviewcontextmenu

Find node clicked under context menu


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.


Solution

  • 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);
            }
        }
    }