TreeNode Right Click Option

zack picture zack · Sep 18, 2009 · Viewed 13k times · Source

I am working TreeView and TreeView.Nodes in my C# GUI application and want to use the right click functionality on a few nodes in my tree. I have searched quite a bit but it seems like the SelectedNode is valid only for left click and there is nothing to capture the right click on a node. I want to add functionalities like 'Add', 'Remove', 'Rename', etc. to the nodes when right clicked upon. Any guidance please?

Thanks, Viren

Answer

Scott Langham picture Scott Langham · Sep 18, 2009

Add a handler for MouseUp. In the handler, check the args for a right mouse button, return if it's not. Call treeView.GetNodeAt() with the mouse coordinates to find the node. Create a context menu.

Here's something similar for a list control which can be adapted for a TreeView:

        private void listJobs_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                int index = listJobs.IndexFromPoint(e.Location);
                if (index != ListBox.NoMatches)
                {
                    listJobs.SelectedIndex = index;

                    Job job = (Job)listJobs.Items[index];

                    ContextMenu cm = new ContextMenu();


                    AddMenuItem(cm, "Run", QueueForRun, job).Enabled = !job.Pending;
                    AddMenuItem(cm, "Cancel run", CancelQueueForRun, job).Enabled = (job.State == JobState.Pending || job.State == JobState.Running);
                    AddMenuItem(cm, "Open folder", OpenFolder, job);

                    cm.Show(listJobs, e.Location);
                }
            }
        }

        private MenuItem AddMenuItem(ContextMenu cm, string text, EventHandler handler,     object context)
        {
            MenuItem item = new MenuItem(text, handler);
            item.Tag = context;
            cm.MenuItems.Add(item);
            return item;
        }

You may need to use PointToClient or PointToScreen on the form to translate the coordinates appropriately. You'll soon realize if you need them when the context menu appears in the wrong place.