1 using System.Collections;
2 using System.Drawing;
3 using System.IO;
4 using System.Linq;
5 using System.Windows.Forms;
6
7 namespace menuTreeWITHrightMouseClick
8 {
9 public partial class Form1 : Form
10 {
11 string strRootFolderPath = @"D:\CODE";
12 TreeNode rootNode;
13
14 public Form1()
15 {
16 InitializeComponent();
17 rootNode = new TreeNode(strRootFolderPath);
18 BangdingTreeView(rootNode);
19 this.tv_Folders.Nodes.Add(rootNode);
20 this.tv_Folders.CollapseAll();
21 int a = this.tv_Folders.GetNodeCount(true);
22 }
23
24 private void BangdingTreeView(TreeNode tr)
25 {
26 foreach (string strPath in Directory.GetDirectories(tr.Text))
27 {
28 TreeNode currentNode = new TreeNode(strPath);
29 GetTreeNodesStatus(tv_Folders.Nodes);
30 tr.Nodes.Add(currentNode);
31 //更新TreeView函数
32 SetTreeNodesStatus(tv_Folders.Nodes);
33 if (Directory.GetDirectories(strPath).Count() > 0)
34 {
35 BangdingTreeView(currentNode);
36 }
37 }
38 }
39
40 private Hashtable NodesStatus = new Hashtable();
41 private string SelectNodeFullPath = string.Empty;
42
43 private void GetTreeNodesStatus(TreeNodeCollection nodes)
44 {
45 foreach (TreeNode node in nodes)
46 {
47 if (node.IsExpanded)
48 {
49 NodesStatus[node.FullPath] = true;
50 }
51 else
52 {
53 NodesStatus.Remove(node.FullPath);
54 }
55 if (node.IsSelected)
56 {
57 SelectNodeFullPath = node.FullPath;
58 }
59 GetTreeNodesStatus(node.Nodes);
60 }
61 }
62
63 private void SetTreeNodesStatus(TreeNodeCollection nodes)
64 {
65 foreach (TreeNode node in nodes)
66 {
67 if (NodesStatus[node.FullPath] != null)
68 {
69 node.Expand();
70 }
71 if (node.FullPath == SelectNodeFullPath)
72 {
73 this.tv_Folders.SelectedNode = node;
74 }
75 SetTreeNodesStatus(node.Nodes);
76 }
77 }
78
79 private void tv_Folders_MouseDown(object sender, MouseEventArgs e)
80 {
81 if (e.Button == MouseButtons.Right)//判断点击的是否是右键
82 {
83 Point ClickPoint = new Point(e.X, e.Y);//获取鼠标点击的坐标
84 TreeNode CurrentNode = tv_Folders.GetNodeAt(ClickPoint);//在获取的坐标处找节点
85 if (CurrentNode != null)//判断点击的位置有没有节点
86 {
87 CurrentNode.ContextMenuStrip = ctm_rightClickMenus;//给当前获取到的节点属性绑定右键点击事件
88 string name = tv_Folders.SelectedNode.Text.ToString();//存储节点文本
89 tv_Folders.SelectedNode = CurrentNode;//把点击获取到的节点设置为选中状态
90 }
91 }
92 }
93
94 private void tv_Folders_AfterSelect(object sender, TreeViewEventArgs e)
95 {
96
97 }
98 }
99 }