Welcome to WindowsClient.net | Sign in | Join

Here are some frequently asked questions about Windows Forms and their answers.

Windows Forms FAQs

How do I display a ContextMenu when the user right-clicks on a node in a TreeView control?

You can display a context menu when a user right-clicks on a node by handling the TreeView's MouseUp event as shown below:

[C#]

private void treeView1_MouseUp( object sender, MouseEventArgs e )
{
  if ( e.Button == MouseButtons.Right )
  {
    Point clickPoint = new Point( e.X,e.Y );
    TreeNode clickNode = treeView1.GetNodeAt( clickPoint );
    if ( clickNode == null ) return;

    // Convert from Tree coordinates to Screen coordinates
    Point screenPoint = treeView1.PointToScreen( clickPoint );

    // Convert from Screen coordinates to Form coordinates
    Point formPoint = PointToClient( screenPoint );

    // Show context menu
    contextmenu.MenuItems.Clear();
    contextmenu.MenuItems.Add( "Item1" );
    contextmenu.MenuItems.Add( "Item2" );
    contextmenu.Show( this, FormPoint );
  }
}

Contributed from George Shepherd's Windows Forms FAQ