每次右键单击vb.net都会显示上下文菜单

时间:2015-12-06 07:10:36

标签: vb.net treeview behavior right-click

我正在尝试向vb.net中的树视图添加上下文菜单,但我没有得到所需的行为。当我在树视图中右键单击时,我能够根据用户点击的位置显示具有不同选项的上下文菜单,但如果用户单击树视图中的其他位置并且上下文菜单已经启动,则上下文菜单只会清除并执行不会重新出现在新单击的位置(非常类似于在Web浏览器中多次右键单击)。

这是我到目前为止所做的:

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

无论如何在vb.net中都有这种行为吗?

1 个答案:

答案 0 :(得分:0)

我认为您不需要在MouseDown事件中编写任何代码。您需要做的是 - 在填充ContextMenu时正确设置每个Node的{​​{1}}。

如果我是你,我会做这样的事情

TreeView