使用命令行参数

时间:2018-04-19 14:47:38

标签: c# winapi

我正在尝试使用CreateProcessAsUser启动进程并且工作正常但是如果存在命令行参数,则函数失败并且最后一个错误设置为ERROR_UNKNOWN_REVISION。

我为命令行尝试了多种组合而没有运气。

这是代码

    var CMD_ARGS = Environment.GetCommandLineArgs();

        string FILE_NAME = EntryPoint.PRCOESS_FILE_NAME;
        string WORKING_DIRECTORY = EntryPoint.PROCESS_DIRECTORY;
        string ARGUMENTS = CMD_ARGS.Skip(1).Aggregate((first,next)=> ' ' + first + ' ' + next);

        IntPtr USER_TOKEN = IntPtr.Zero;
        IntPtr ENVIRONMENT=IntPtr.Zero;

        try
        {
            var consoleSession = Kernel32.WTSGetActiveConsoleSessionId();
            if (consoleSession == 0xFFFFFFFF)
                return;

            if (!Wtsapi32.WTSQueryUserToken(consoleSession, out USER_TOKEN))
                throw new Win32Exception();

            if (!Userenv.CreateEnvironmentBlock(out ENVIRONMENT, USER_TOKEN, true))
                throw new Win32Exception();                   

            //initialize structures
            SECURITY_ATTRIBUTES sa = new SECURITY_ATTRIBUTES();
            sa.nLength = Marshal.SizeOf(sa);

            //initialize startup
            STARTUPINFO si = new STARTUPINFO();
            si.cb = Marshal.SizeOf(si);

            //initialize process info
            var PROCESS_INFO = new PROCESS_INFORMATION();

            int dwCreationFlags = NORMAL_PRIORITY_CLASS | (int)(PROCESS_CREATE_FLAG.CREATE_NEW_CONSOLE | PROCESS_CREATE_FLAG.CREATE_UNICODE_ENVIRONMENT);

            if (!AdvApi32.CreateProcessAsUser(USER_TOKEN,
                FILE_NAME,
                ARGUMENTS,
                ref sa,
                ref sa,
                true,
                dwCreationFlags,
                ENVIRONMENT,
                WORKING_DIRECTORY,
                ref si,
                out PROCESS_INFO))
                throw new Win32Exception();

            if (PROCESS_INFO.hThread != IntPtr.Zero)
            {
                ClientProcessId = PROCESS_INFO.dwProcessId;
                ClientSessionId = consoleSession;
                Trace.WriteLine($"{PROCESS_INFO.dwProcessId}");
            }
        }
        catch(Exception ex)
        {
            throw;
        }
        finally
        {
            Userenv.DestroyEnvironmentBlock(ENVIRONMENT);
            Kernel32.CloseHandle(USER_TOKEN);
        }

0 个答案:

没有答案