I am trying to add a context menu to a treeview in vb.net but am not getting the desired behavior. When I right click in the treeview I am able to get a context menu to appear with different options based on where the user clicks, but if the user clicks elsewhere in the treeview and a context menu is already up the context menu simply clears and does not reappear in the new clicked location (much like right clicking multiple times in a web browser).
This is what I have so far:
Private Sub treeviewMain_MouseDown(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles treeviewMain.MouseDown
If e.Button = Windows.Forms.MouseButtons.Right Then
'Determine which tree structure is loaded in tree view.
If (treeviewMain.Nodes.Item(0).Name = "MainNode") Then
Test(sender, e)
Else
OtherTest(sender, e)
End If
End If
End Sub
Private Sub Test(sender As Object, e As System.Windows.Forms.MouseEventArgs)
Dim Context As ContextMenu = New ContextMenu
Dim NodeClicked As TreeNode
NodeClicked = Me.tvwMain.GetNodeAt(e.X, e.Y)
If NodeClicked Is Nothing Then
Context.MenuItems.Add("New Item")
Context.Show(treeviewMain, e.Location)
ElseIf NodeClicked.Name = "MainNode" Then
tvwMain.SelectedNode = NodeClicked
Context.MenuItems.Add("New Item")
Context.Show(treeviewMain, e.Location)
ElseIf NodeClicked.Level = 0 And NodeClicked.Name <> "MainNode" Then
tvwMain.SelectedNode = NodeClicked
Context.MenuItems.Add("Rename")
Context.MenuItems.Add("Delete")
Context.MenuItems.Add("-")
Context.MenuItems.Add("New")
Context.Show(treeviewMain, e.Location)
ElseIf NodeClicked.Level = 1 Then
tvwMain.SelectedNode = NodeClicked
Context.MenuItems.Add("Edit")
Context.MenuItems.Add("Copy")
Context.MenuItems.Add("Delete")
Context.Show(treeviewMain, e.Location)
End If
End Sub
Is there anyway to get this behavior in vb.net?