Search code examples
vb.netwinformstreeviewtreenodedeselect

Treeview .Click and .MouseClick event not firing when no node is clicked


I want to set the selected node to nothing if a user clicks on the treeview (right or left) and the cursor is not on a node. I thought the TreeView.MouseClick event would fire if any part of the control was clicked, but it seems only to fire when a node is clicked. Is there any way to do this?

Edit* I do know how to set the selected node to nothing, tvwMain.SelectedNode = Nothing but am unable to do so when the control is clicked and there is no node at that point as the TreeView.MouseClick and TreeView.Click events do not seem to fire unless a node is clicked.

Private Sub tvwMain_NodeMouseClick(sender As Object, e As MouseEventArgs) Handles tvwMain.Click
    Dim p = New Point(e.X, e.Y)
    Dim node As TreeNode = tvwMain.GetNodeAt(p)

    If node IsNot Nothing Then
        tvwMain.SelectedNode = node
        MsgBox("HERE")
    Else
        tvwMain.SelectedNode = Nothing
        MsgBox("TOO")
    End If
End Sub

Solution

  • TreeNode test = tvwMain.GetNodeAt(tvwMain.PointToClient(Cursor.Position))
    If IsNothing(test) Then tvwMain.SelectedNode = Nothing