NodeSelectionDialog.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Text;
  9. using System.Text.RegularExpressions;
  10. using System.Threading.Tasks;
  11. using System.Windows.Forms;
  12. using System.Xml.Linq;
  13. using System.Xml.Serialization;
  14. namespace XmlToTreeView
  15. {
  16. public partial class NodeSelectionDialog : Form
  17. {
  18. private Node selectedValue;
  19. public Node SelectedValue { get => selectedValue; set => selectedValue = value; }
  20. static readonly string ConfigPath = @"D:\XmlParser\Config.txt";
  21. static readonly string TreeViewState = @"D:\XmlParser\treeview_state.xml";
  22. public NodeSelectionDialog()
  23. {
  24. InitializeComponent();
  25. }
  26. private void NodeSelectionDialog_Load(object sender, EventArgs e)
  27. {
  28. this.Size = new System.Drawing.Size(1024, 768);
  29. if (File.Exists(ConfigPath))
  30. {
  31. var xmlPath = File.ReadAllText(ConfigPath);
  32. LoadTree(xmlPath,false);
  33. }
  34. LoadTreeViewState(treeView);
  35. txtSearch.Focus();
  36. }
  37. private void LoadTree(string xmlPath,bool isUserLoad)
  38. {
  39. if (!File.Exists(xmlPath))
  40. {
  41. return;
  42. }
  43. try
  44. {
  45. var types = SymbolParser.ParseTypeList(xmlPath);
  46. var root = SymbolParser.ParseNode(xmlPath, types);
  47. treeView.Nodes.Clear();
  48. AddToTreeView(treeView.Nodes, root);
  49. foreach (TreeNode node in treeView.Nodes)
  50. {
  51. node.Expand();
  52. }
  53. if (isUserLoad)//只有用户打开的时候才去保存
  54. {
  55. FileInfo fileInfo = new FileInfo(ConfigPath);
  56. DirectoryInfo dir = fileInfo.Directory;
  57. Directory.CreateDirectory(dir.FullName);
  58. File.WriteAllText(ConfigPath, xmlPath);
  59. Node.AllNodes = new List<string>();
  60. GenerateFullPaths(root, Node.AllNodes);
  61. File.WriteAllLines(Node.NodeFilePath, Node.AllNodes.ToArray());
  62. }
  63. }
  64. catch (Exception ex)
  65. {
  66. MessageBox.Show(ex.Message,"错误",MessageBoxButtons.OK, MessageBoxIcon.Error);
  67. return;
  68. }
  69. }
  70. private void AddToTreeView(TreeNodeCollection nodes, XmlVariable variableNode)
  71. {
  72. TreeNode tn = new TreeNode(variableNode.DisplayName);
  73. tn.Tag = variableNode.Name;
  74. foreach (var child in variableNode.Children)
  75. {
  76. AddToTreeView(tn.Nodes, child);
  77. }
  78. nodes.Add(tn);
  79. }
  80. private string GetFullPath(TreeNode node)
  81. {
  82. List<string> pathParts = new List<string>();
  83. TreeNode currentNode = node;
  84. while (currentNode != null)
  85. {
  86. // 获取当前节点显示的文本
  87. pathParts.Add(currentNode.Tag.ToString());
  88. // 获取父节点
  89. currentNode = currentNode.Parent;
  90. }
  91. pathParts.Reverse(); // 从根到叶子排列
  92. return string.Join(".", pathParts);
  93. }
  94. private void GenerateFullPaths(XmlVariable root, List<string> paths, string currentPath = "")
  95. {
  96. string newPath = string.IsNullOrEmpty(currentPath) ? root.Name : $"{currentPath}.{root.Name}";
  97. if (root.IsLeaf)
  98. {
  99. paths.Add(ProcessArrayPath(newPath));
  100. }
  101. else
  102. {
  103. foreach (var child in root.Children)
  104. {
  105. GenerateFullPaths(child, paths, newPath);
  106. }
  107. }
  108. }
  109. string ProcessArrayPath(string path)
  110. {
  111. // 第一步:去掉 .[ 前面的点,变成 [
  112. string result = path;
  113. while (true)
  114. {
  115. int index = result.IndexOf(".[", StringComparison.Ordinal);
  116. if (index == -1) break;
  117. result = result.Substring(0, index) + "[" + result.Substring(index + 2);
  118. }
  119. // 第二步:合并 [1][2] → [1,2]
  120. while (true)
  121. {
  122. int index = result.IndexOf("][", StringComparison.Ordinal);
  123. if (index == -1) break;
  124. // 替换 ][ 为 ,,并删除多余的 ]
  125. result = result.Substring(0, index) + "," + result.Substring(index + 2);
  126. }
  127. return result;
  128. }
  129. private void 打开XMLOToolStripMenuItem_Click(object sender, EventArgs e)
  130. {
  131. OpenFileDialog openFileDialog = new OpenFileDialog();
  132. openFileDialog.Filter = "XML文档|*.xml";
  133. openFileDialog.Multiselect = false;
  134. openFileDialog.RestoreDirectory = true;
  135. if (openFileDialog.ShowDialog() == DialogResult.OK)
  136. {
  137. LoadTree(openFileDialog.FileName,true);
  138. }
  139. }
  140. private void treeView_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
  141. {
  142. if (e.Node.Nodes.Count > 0)
  143. return;
  144. var currentNode = treeView.GetNodeAt(e.X, e.Y);
  145. if (currentNode != null)
  146. {
  147. string fullPath = GetFullPath(currentNode);
  148. txtNode.Text = ProcessArrayPath(fullPath);
  149. txtType.Text = GetTypeString(currentNode.Text,'(',')');
  150. txtComment.Text = GetTypeString(currentNode.Text, '<', '>');
  151. }
  152. }
  153. string GetTypeString(string nodeTxt,char spliter1, char spliter2)
  154. {
  155. int startIndex = nodeTxt.LastIndexOf(spliter1);
  156. int endIndex = nodeTxt.LastIndexOf(spliter2);
  157. if (startIndex >= 0 && endIndex > startIndex)
  158. {
  159. string result = nodeTxt.Substring(startIndex + 1, endIndex - startIndex - 1);
  160. return result;
  161. }
  162. return null;
  163. }
  164. bool userSelectedNode;
  165. private void treeView_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
  166. {
  167. if (e.Node.Nodes.Count > 0)
  168. return;
  169. var currentNode = treeView.GetNodeAt(e.X, e.Y);
  170. if (currentNode != null)
  171. {
  172. string fullPath = GetFullPath(currentNode);
  173. string rt = ProcessArrayPath(fullPath);
  174. txtNode.Text = rt;
  175. var typeString= GetTypeString(currentNode.Text, '(', ')');
  176. bool isDefinedType = Enum.TryParse<NodeType>(typeString, out NodeType type) && Enum.IsDefined(typeof(NodeType), type);
  177. if (isDefinedType)
  178. {
  179. SelectedValue = new Node(rt, type, GetTypeString(currentNode.Text, '<', '>'));
  180. DialogResult = DialogResult.OK;
  181. userSelectedNode = true;
  182. Close();
  183. }
  184. else
  185. {
  186. MessageBox.Show($"暂不支持:{typeString}类型数据","错误",MessageBoxButtons.OK,MessageBoxIcon.Error);
  187. return;
  188. }
  189. }
  190. }
  191. private void LoadTreeViewState(System.Windows.Forms.TreeView treeView)
  192. {
  193. if (!File.Exists(TreeViewState)) return;
  194. using (FileStream fs = new FileStream(TreeViewState, FileMode.Open))
  195. {
  196. XmlSerializer serializer = new XmlSerializer(typeof(TreeViewState));
  197. var state = (TreeViewState)serializer.Deserialize(fs);
  198. // 恢复展开状态
  199. foreach (var node in GetAllNodes(treeView.Nodes))
  200. {
  201. if (state.ExpandedNodeKeys.Contains(GetNodeKey(node)))
  202. {
  203. node.Expand();
  204. }
  205. }
  206. // 恢复选中状态
  207. if (!string.IsNullOrEmpty(state.SelectedNodeKey))
  208. {
  209. TreeNode selectedNode = FindNodeByPath(treeView, state.SelectedNodeKey);
  210. if (selectedNode != null)
  211. {
  212. treeView.SelectedNode = selectedNode;
  213. string fullPath = GetFullPath(selectedNode);
  214. txtNode.Text = ProcessArrayPath(fullPath);
  215. }
  216. }
  217. }
  218. }
  219. // 根据 FullPath 查找节点
  220. private TreeNode FindNodeByPath(System.Windows.Forms.TreeView treeView, string fullPath)
  221. {
  222. foreach (var node in GetAllNodes(treeView.Nodes))
  223. {
  224. if (((TreeNode)node).FullPath == fullPath)
  225. {
  226. return (TreeNode)node;
  227. }
  228. }
  229. return null;
  230. }
  231. private void NodeSelectionDialog_FormClosed(object sender, FormClosedEventArgs e)
  232. {
  233. if(userSelectedNode)
  234. SaveTreeViewState(treeView);
  235. }
  236. private void SaveTreeViewState(System.Windows.Forms.TreeView treeView)
  237. {
  238. TreeViewState state = new TreeViewState();
  239. // 保存选中节点
  240. if (treeView.SelectedNode != null)
  241. {
  242. state.SelectedNodeKey = GetNodeKey(treeView.SelectedNode);
  243. }
  244. // 保存所有已展开的节点
  245. foreach (TreeNode node in GetAllNodes(treeView.Nodes))
  246. {
  247. if (node.IsExpanded)
  248. {
  249. state.ExpandedNodeKeys.Add(GetNodeKey(node));
  250. }
  251. }
  252. // 使用序列化保存到文件或其他地方
  253. using (FileStream fs = new FileStream(TreeViewState, FileMode.Create))
  254. {
  255. XmlSerializer serializer = new XmlSerializer(typeof(TreeViewState));
  256. serializer.Serialize(fs, state);
  257. }
  258. }
  259. // 获取唯一标识符(可以是 FullPath、Text 或你自己设计的 Key)
  260. private string GetNodeKey(TreeNode node)
  261. {
  262. return node.FullPath;
  263. }
  264. // 遍历所有节点(递归)
  265. private IEnumerable<TreeNode> GetAllNodes(TreeNodeCollection nodes)
  266. {
  267. foreach (TreeNode node in nodes)
  268. {
  269. yield return node;
  270. foreach (var child in GetAllNodes(node.Nodes))
  271. {
  272. yield return child;
  273. }
  274. }
  275. }
  276. private void btnSearch_Click(object sender, EventArgs e)
  277. {
  278. string searchText = txtSearch.Text.Trim();
  279. if (string.IsNullOrEmpty(searchText)) return;
  280. treeView.SelectedNode = null;
  281. _firstMatchNode = null;
  282. matchCount = 0;
  283. CollapseAllNodes(treeView);
  284. FindAndExpandNodes(treeView,txtSearch.Text);
  285. // 如果有第一个匹配项,手动滚动到顶部
  286. if (_firstMatchNode != null && matchCount>1)
  287. {
  288. // 先确保节点可见(再次调用,避免 EnsureVisible 未生效)
  289. _firstMatchNode.EnsureVisible();
  290. // 使用反射或 API 设置滚动条位置到顶部
  291. ScrollTreeViewToTopLeft(treeView, _firstMatchNode);
  292. }
  293. }
  294. private TreeNode _firstMatchNode = null;
  295. int matchCount = 0;
  296. private void FindAndExpandNodes(System.Windows.Forms.TreeView treeView, string searchText)
  297. {
  298. if (string.IsNullOrEmpty(searchText)) return;
  299. foreach (var item in foundedNodes)
  300. {
  301. item.BackColor = Color.Transparent;
  302. }
  303. foundedNodes.Clear();
  304. foreach (TreeNode node in treeView.Nodes)
  305. {
  306. SearchNodeRecursively(node, searchText);
  307. }
  308. }
  309. List<TreeNode> foundedNodes=new List<TreeNode> ();
  310. private bool SearchNodeRecursively(TreeNode node, string searchText)
  311. {
  312. bool found = false;
  313. // 先检查当前节点是否匹配
  314. if (node.Text.IndexOf(searchText, StringComparison.OrdinalIgnoreCase) >= 0)
  315. {
  316. node.Expand(); // 展开当前节点
  317. node.EnsureVisible(); // 确保节点可见
  318. if (treeView.SelectedNode == null)
  319. {
  320. treeView.SelectedNode = node; // 选中第一个匹配的节点
  321. }
  322. Color color = node.BackColor;
  323. node.BackColor = Color.LimeGreen;
  324. //var timer = new Timer() { Tag = node, Interval = 10000 };
  325. //timer.Tick += (object s, EventArgs e) => { ((TreeNode)((Timer)s).Tag).BackColor = Color.Transparent; ((Timer)s).BackgroundRefreshEnable = false; };
  326. //timer.Start();
  327. foundedNodes.Add(node);
  328. if (_firstMatchNode == null)
  329. {
  330. _firstMatchNode = node; // 记录第一个匹配的节点
  331. }
  332. matchCount++;
  333. found = true;
  334. }
  335. // 再检查子节点
  336. foreach (TreeNode child in node.Nodes)
  337. {
  338. if (SearchNodeRecursively(child, searchText))
  339. {
  340. matchCount++;
  341. found = true;
  342. node.Expand(); // 如果子节点匹配,父节点也要展开
  343. }
  344. }
  345. return found;
  346. }
  347. private void CollapseAllNodes(System.Windows.Forms.TreeView treeView)
  348. {
  349. foreach (TreeNode node in treeView.Nodes)
  350. {
  351. CollapseNodeRecursively(node);
  352. }
  353. }
  354. private void CollapseNodeRecursively(TreeNode node)
  355. {
  356. if (node.IsExpanded)
  357. {
  358. node.Collapse(); // 折叠当前节点
  359. }
  360. foreach (TreeNode child in node.Nodes)
  361. {
  362. CollapseNodeRecursively(child); // 递归处理子节点
  363. }
  364. }
  365. [System.Runtime.InteropServices.DllImport("user32.dll")]
  366. private static extern int SendMessage(IntPtr hWnd, int wMsg, IntPtr wParam, IntPtr lParam);
  367. private const int WM_VSCROLL = 0x0115;
  368. private const int WM_HSCROLL = 0x0114;
  369. private const int SB_TOP = 6;
  370. private const int SB_LEFT = 6;
  371. private void ScrollTreeViewToTopLeft(System.Windows.Forms.TreeView treeView, TreeNode node)
  372. {
  373. // 确保节点可见(垂直方向)
  374. node.EnsureVisible();
  375. // 垂直滚动到顶部
  376. SendMessage(treeView.Handle, WM_VSCROLL, (IntPtr)SB_TOP, IntPtr.Zero);
  377. // 水平滚动到最左边
  378. SendMessage(treeView.Handle, WM_HSCROLL, (IntPtr)SB_LEFT, IntPtr.Zero);
  379. }
  380. private void txtNode_DoubleClick(object sender, EventArgs e)
  381. {
  382. txtNode.SelectAll();
  383. }
  384. private void txtSearch_Click(object sender, EventArgs e)
  385. {
  386. txtSearch.SelectAll();
  387. }
  388. }
  389. [Serializable]
  390. public class TreeViewState
  391. {
  392. public string SelectedNodeKey { get; set; }
  393. public List<string> ExpandedNodeKeys { get; set; } = new List<string>();
  394. public List<string> AllNodes { get; set; } = new List<string>();
  395. }
  396. }