public static List<Proc> getProcessTree(PacketStatistic statistic) { var relations = new Dictionary<int, List<int>>(); var procs = new Dictionary<int, Proc>(); var searcher = new ManagementObjectSearcher("select * from win32_process"); foreach(var res in searcher.Get()) { // res info at https://msdn.microsoft.com/en-us/library/aa394372(v=vs.85).aspx int pid = Convert.ToInt32(res["ProcessId"].ToString()); int ppid = Convert.ToInt32(res["ParentProcessId"].ToString()); string name = res["Name"].ToString(); procs[pid] = new Proc() { processId = pid, parentId = ppid, processName = name }; } var dataCount = statistic.refreshData(); var pc = new ProcessConnection(); foreach(var con in pc.connections) { if (con.pid != 0 && procs.ContainsKey(con.pid)) { procs[con.pid].connections.Add(con); if (dataCount.ContainsKey(con)) { procs[con.pid].speed += dataCount[con]; } } } var children = new HashSet<int>(); foreach(var res in procs) { int pid = res.Value.processId; int ppid = res.Value.parentId; if (ppid != 0 && procs.ContainsKey(ppid)) { procs[ppid].children.Add(procs[pid]); children.Add(pid); } } var result = new List<Proc>(); foreach (var res in procs) { if(!children.Contains(res.Key)) { result.Add(res.Value); } } return result; }
private TreeNode buildTreeNode(Proc proc) { string info; if (proc.connections.Count == 0) { info = string.Format("{0} (pid:{1})", proc.processName, proc.processId); } else { info = string.Format("{0} (pid :{1} - {2} connections - {3} Byte/s )", proc.processName, proc.processId, proc.connections.Count,proc.speed); } var res = new TreeNode(info); res.Name = string.Format("{0}", proc.processId); foreach(Proc child in proc.children) { res.Nodes.Add(buildTreeNode(child)); } return res; }