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 Form 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 Form 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
Share with