XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet

XFEWorkflow

【WinUI】XFE基于windows的工作流

公开
关注 0 Fork 0 Star 0
UTF-8
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<int> processIds,
        IReadOnlyCollection<int> processesWithMainWindows)
    {
        HashSet<int> 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<int> processIds,
        IReadOnlyDictionary<int, int> parents)
    {
        HashSet<int> 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<int, int> ReadParents()
    {
        using Snapshot snapshot = Native.CreateToolhelp32Snapshot(0x00000002, 0);
        if (snapshot.IsInvalid) throw new Win32Exception(Marshal.GetLastWin32Error());
        ProcessEntry entry = new() { Size = (uint)Marshal.SizeOf<ProcessEntry>(), Executable = "" };
        Dictionary<int, int> 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);
    }
}