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

XFEToolBox

【WPF】XFE工具箱

公开
关注 0 Fork 0 Star 0
UTF-8
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Text;
using Microsoft.Win32.SafeHandles;

namespace XFEToolBox.Client.Installer.Utilities;

/// <summary>Launching from the elevated installer must not elevate the desktop application.</summary>
internal static class UnelevatedApplicationLauncher
{
    public static void Start(string executablePath, string workingDirectory)
    {
        if (!new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator))
        {
            if (Process.Start(new ProcessStartInfo(executablePath) { UseShellExecute = true, WorkingDirectory = workingDirectory }) is null)
                throw new InvalidOperationException("系统未能创建应用进程。");
            return;
        }

        var shell = GetShellWindow();
        if (shell == IntPtr.Zero) throw new InvalidOperationException("未找到普通权限桌面,请从桌面快捷方式启动 XFEToolBox。");
        GetWindowThreadProcessId(shell, out var shellProcessId);
        using var shellProcess = OpenProcess(0x1000, false, shellProcessId);
        if (shellProcess.IsInvalid) throw new Win32Exception(Marshal.GetLastWin32Error());
        if (!OpenProcessToken(shellProcess, 0x0002 | 0x0008, out var shellToken))
            throw new Win32Exception(Marshal.GetLastWin32Error());
        using (shellToken)
        {
            if (!GetTokenInformation(shellToken, 20, out var elevated, sizeof(int), out _) || elevated != 0)
                throw new InvalidOperationException("无法确认桌面进程为普通权限,请从普通权限桌面手动启动 XFEToolBox。");
            if (!DuplicateTokenEx(shellToken, 0x02000000, IntPtr.Zero, 2, 1, out var primaryToken))
                throw new Win32Exception(Marshal.GetLastWin32Error());
            using (primaryToken)
            {
                if (!CreateEnvironmentBlock(out var environment, primaryToken, false))
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                try
                {
                    var startup = new StartupInfo { Size = Marshal.SizeOf<StartupInfo>() };
                    var commandLine = new StringBuilder('"' + executablePath + '"');
                    if (!CreateProcessWithTokenW(primaryToken, 1, executablePath, commandLine, 0x400,
                            environment, workingDirectory, ref startup, out var process))
                        throw new Win32Exception(Marshal.GetLastWin32Error(), "无法以普通用户权限启动,请从桌面快捷方式打开 XFEToolBox。");
                    CloseHandle(process.Thread);
                    CloseHandle(process.Process);
                }
                finally { DestroyEnvironmentBlock(environment); }
            }
        }
    }

    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
    private struct StartupInfo
    {
        public int Size;
        public string? Reserved, Desktop, Title;
        public int X, Y, XSize, YSize, XCountChars, YCountChars, FillAttribute, Flags;
        public short ShowWindow, ReservedLength;
        public IntPtr ReservedBytes, StandardInput, StandardOutput, StandardError;
    }
    [StructLayout(LayoutKind.Sequential)] private struct ProcessInformation { public IntPtr Process, Thread; public uint ProcessId, ThreadId; }
    [DllImport("user32.dll")] private static extern IntPtr GetShellWindow();
    [DllImport("user32.dll")] private static extern uint GetWindowThreadProcessId(IntPtr window, out uint processId);
    [DllImport("kernel32.dll", SetLastError = true)] private static extern SafeProcessHandle OpenProcess(uint access, bool inherit, uint processId);
    [DllImport("advapi32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)]
    private static extern bool OpenProcessToken(SafeProcessHandle process, uint access, out SafeAccessTokenHandle token);
    [DllImport("advapi32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)]
    private static extern bool GetTokenInformation(SafeAccessTokenHandle token, int information, out int elevation, int length, out int returned);
    [DllImport("advapi32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)]
    private static extern bool DuplicateTokenEx(SafeAccessTokenHandle token, uint access, IntPtr attributes, int impersonation, int type, out SafeAccessTokenHandle duplicate);
    [DllImport("userenv.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)]
    private static extern bool CreateEnvironmentBlock(out IntPtr environment, SafeAccessTokenHandle token, bool inherit);
    [DllImport("userenv.dll")] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool DestroyEnvironmentBlock(IntPtr environment);
    [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)]
    private static extern bool CreateProcessWithTokenW(SafeAccessTokenHandle token, uint logonFlags, string application, StringBuilder commandLine,
        uint creationFlags, IntPtr environment, string directory, ref StartupInfo startup, out ProcessInformation process);
    [DllImport("kernel32.dll")] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool CloseHandle(IntPtr handle);
}