Add Popup Menus To TreeView Controls

The problem is that the TreeView control does not support right click menus. There is no easy way to tell what mouse button was pushed to cause a NodeClick event.

The code below, when used in a TreeView MouseUp event, will capture the specific node that a right mouse button is clicked on, allowing you to popup a custom menu for that node.


Private Sub TreeView1_MouseUp(Button As Integer, Shift As Integer, x As Single, y As Single)
Dim nod As Node
     If Button = vbRightButton Then
           Set nod = TreeView1.HitTest(x, y)
           On Error GoTo EmptyNode
           nod.Selected = True
           On Error GoTo 0
           '<<Customize menu here>>
           Me.PopupMenu mnuPopUp
           On Error GoTo 0
     End If
End Sub


This tip is reprinted from the VB Tips & Tricks Volume 1 book.
Parts of this tip was submitted by: Scott D. Killen