使用Winform的TreeView控件时,经常会有这样的需求:
(1).要求每个节点的右键菜单显示的内容不同。
(2).要求在整个控件的空白区域点击右键的时候也能显示菜单。
在实际运用中发现,如果单纯的要满足第一个条件,我们只需要在mouseclick事件中进行一些节点的判断,然后进行菜单的显示就行了,参考代码如下:
1 private void treeViewWindows_MouseClick(object sender, MouseEventArgs e) 2 { 3 if (MouseButtons.Right == e.Button) 4 { 5 WinSelect = new TreeNode(); 6 WinSelect = treeViewWindows.GetNodeAt(e.X, e.Y); 7 treeViewWindows.SelectedNode = WinSelect; 8 toolStripMenuItemWinRefresh.Enabled = true; 9 if (WinSelect != null) 10 { 11 //此处添加选中节点后的菜单显示 12 } 13 else 14 { 15 //此处添加空白区域的菜单显示 16 } 17 contextMenuStripDeskWin.Show(Cursor.Position); 18 }
但是在实际运行中发现无论怎么在空白区域右键点击,都无法弹出菜单。
查找了一些其他博主的文章发现是因为TreeView默认绑定了右键菜单控件ContextMenuStrip,即使你没有去定义treeview.contextmenuscript=xxx,它依然不会去响应你的右键click事件。
为了解决这个问题,只需要将我们的触发事件修改为MouseUp或者MouseDown即可。