Serialcoder en Français Serialcoder in English
TEL : +33 (0)9 72 13 15 17

Windows Forms FAQ resources

24. Windows Forms TreeView

24.12 How can I display a context menu when the user right-clicks on a node in the TreeView control?


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

[C#]
private void treeView1_MouseUp(object sender, System.Windows.Forms.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 Formc coordinates
          Point FormPoint = this.PointToClient(ScreenPoint);
          // Show context menu
          contextmenu.MenuItems.Clear();
          contextmenu.MenuItems.Add("Item1");
          contextmenu.MenuItems.Add("Item2");
          contextmenu.Show(this,FormPoint);
     }
}

[VB.NET]
Private Sub treeView1_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs)
     If e.Button = MouseButtons.Right Then
          Dim ClickPoint As Point = New Point(e.X,e.Y)
          Dim ClickNode As TreeNode = treeView1.GetNodeAt(ClickPoint)
          If ClickNode Is Nothing Then
                Return
          End If
          ' Convert from Tree coordinates to Screen coordinates
          Dim ScreenPoint As Point = treeView1.PointToScreen(ClickPoint)
          ' Convert from Screen coordinates to Formc coordinates
          Dim FormPoint As Point = Me.PointToClient(ScreenPoint)
          ' Show context menu
          contextmenu.MenuItems.Clear()
          contextmenu.MenuItems.Add("Item1")
          contextmenu.MenuItems.Add("Item2")
          contextmenu.Show(this,FormPoint)
     End If
End Sub