CreateProcessAsUser中的参数问题

时间:2011-03-24 14:36:27

标签: vb.net winapi windows-services pinvoke createprocessasuser

我被指派使用VB.NET 2005构建一个能够将进程启动到当前交互式用户的Windows服务。

经过一番研究,我构建了以下代码:

Dim hToken As IntPtr = IntPtr.Zero
Dim LastW32Error As Integer

If WTSQueryUserToken(WTSGetActiveConsoleSessionId(), hToken) Then
        Dim hTokenDup As IntPtr = IntPtr.Zero
        If DuplicateTokenEx(hToken, MAXIMUM_ALLOWED, Nothing, SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, TOKEN_TYPE.TokenPrimary, hTokenDup) Then
            Dim hEnv As IntPtr = IntPtr.Zero
            If CreateEnvironmentBlock(hEnv, hTokenDup, False) Then
                Dim strCommandLine As String = "c:\\windows\\system32\\NotePad.exe"
                Dim saProcessAttributes As SECURITY_ATTRIBUTES = New SECURITY_ATTRIBUTES
                Dim saThreadAttributes As SECURITY_ATTRIBUTES = New SECURITY_ATTRIBUTES
                Dim pi As New PROCESS_INFORMATION
                Dim si As New STARTUPINFO

                saProcessAttributes.nLength = Convert.ToUInt32(Marshal.SizeOf(saProcessAttributes))
                saThreadAttributes.nLength = Convert.ToUInt32(Marshal.SizeOf(saThreadAttributes))
                si.cb = Convert.ToUInt32(Marshal.SizeOf(si))

                If Not CreateProcessAsUser(hTokenDup, Nothing, strCommandLine, saProcessAttributes, saThreadAttributes, False, 0, hEnv, Nothing, si, pi) Then
                    LastW32Error = Marshal.GetLastWin32Error()
                    EvtLog.WriteEntry("CreateProcessAsUser: " + CStr(LastW32Error))
                End If
            Else
                LastW32Error = Marshal.GetLastWin32Error()
                EvtLog.WriteEntry("CreateEnvironmentBlock: " + CStr(LastW32Error))
            End If
            DestroyEnvironmentBlock(hEnv)
        Else
            LastW32Error = Marshal.GetLastWin32Error()
            EvtLog.WriteEntry("DuplicateTokenEx: " + CStr(LastW32Error))
        End If
        CloseHandle(hTokenDup)
Else
    LastW32Error = Marshal.GetLastWin32Error()
    EvtLog.WriteEntry("WTSQueryUserToken: " + CStr(LastW32Error))
End If

CloseHandle(hToken)

但是我在调​​用CreateProcessAsUser时遇到错误87(ERROR_INVALID_PARAMETER)。有人可以指出我做错了什么?

代码实现为在LocalSystem帐户下运行的Windows服务。

1 个答案:

答案 0 :(得分:3)

  • WTSQueryUserToken只能在LocalSystem
  • 下调用
  • WTSQueryUserToken返回一个PrimaryToken。无需重复。
  • 此令牌已具有正确的sessionID和环境(它来自当前登录的用户),因此无需创建环境块