using System.ComponentModel; using System.Runtime.InteropServices; using Microsoft.Win32.SafeHandles; namespace XFEWorkflow.Plugins.WeCom.Native.Integrations; public static class ProcessTree { public static int SelectActiveClient(IReadOnlyCollection processIds, IReadOnlyCollection processesWithMainWindows) { HashSet ids = processIds.ToHashSet(); int[] windowed = processesWithMainWindows.Distinct().ToArray(); if (windowed.Any(id => !ids.Contains(id))) throw new InvalidOperationException("企业微信进程列表已变化,请重试。"); if (windowed.Length == 1) return windowed[0]; if (windowed.Length > 1) throw new InvalidOperationException("存在多个带主窗口的企业微信会话,需要明确指定 PID。"); if (ids.Count == 1) return ids.Single(); throw new InvalidOperationException("无法唯一确定聊天主进程;请显示目标会话的主窗口,或在内存诊断中明确指定 PID。"); } // WXWork starts helper processes with the same executable name. Only a root // whose parent is outside this process set is an independent client candidate. public static int SelectSingleRoot(IReadOnlyCollection processIds, IReadOnlyDictionary parents) { HashSet ids = processIds.ToHashSet(); if (ids.Any(id => !parents.ContainsKey(id))) throw new InvalidOperationException("企业微信进程列表已变化,请重试。"); int[] roots = ids.Where(id => !ids.Contains(parents[id])).ToArray(); if (roots.Length != 1) throw new InvalidOperationException($"检测到 {roots.Length} 个独立企业微信客户端,需要唯一的已登录客户端。"); return roots[0]; } internal static IReadOnlyDictionary ReadParents() { using Snapshot snapshot = Native.CreateToolhelp32Snapshot(0x00000002, 0); if (snapshot.IsInvalid) throw new Win32Exception(Marshal.GetLastWin32Error()); ProcessEntry entry = new() { Size = (uint)Marshal.SizeOf(), Executable = "" }; Dictionary parents = []; bool found = Native.Process32FirstW(snapshot, ref entry); if (!found) throw new Win32Exception(Marshal.GetLastWin32Error()); do { parents[(int)entry.ProcessId] = (int)entry.ParentProcessId; } while (Native.Process32NextW(snapshot, ref entry)); int error = Marshal.GetLastWin32Error(); if (error != 18) throw new Win32Exception(error); // ERROR_NO_MORE_FILES return parents; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] private struct ProcessEntry { internal uint Size, Usage, ProcessId; internal nuint DefaultHeapId; internal uint ModuleId, Threads, ParentProcessId; internal int BasePriority; internal uint Flags; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)] internal string Executable; } private sealed class Snapshot : SafeHandleZeroOrMinusOneIsInvalid { public Snapshot() : base(true) { } protected override bool ReleaseHandle() => Native.CloseHandle(handle); } private static class Native { [DllImport("kernel32.dll", SetLastError = true)] internal static extern Snapshot CreateToolhelp32Snapshot(uint flags, uint processId); [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, ExactSpelling = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool Process32FirstW(Snapshot snapshot, ref ProcessEntry entry); [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, ExactSpelling = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool Process32NextW(Snapshot snapshot, ref ProcessEntry entry); [DllImport("kernel32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool CloseHandle(nint handle); } }