Search
Module:
Directory

   Desktop Functions:

   Smart Device Functions:


Show Recent Changes
Subscribe (RSS)
Misc. Pages
Comments
FAQ
Helpful Tools
Playground
Suggested Reading
Website TODO List
Support Forum
Download Visual Studio Add-In

Terms of Use
Privacy Policy
CreateProcessWithLogonW (advapi32)
 
.
Summary
Starts a new process, opens an application in that process, and uses a passed UserID and Password. The application opened is running under the credentials and authority of the UserID passed.

"Try this for VB"

Imports System.Runtime.InteropServices

Public Structure PROCESS_INFORMATION

    private/Public hProcess As Integer
    private/Public hThread As Integer
    private/Public dwProcessId As Integer
    private/Public dwThreadId As Integer

End Structure

    ' Use this version when the API allocates the strings
    ' (For example: GetStartupInfo)

Structure STARTUPINFO

    Private/Public cb As Integer
    private/Public lpReserved As Integer ' Instead of String!
    private/Public lpDesktop As Integer  ' Instead of String!
    private/Public lpTitle As Integer    ' Instead of String!
    private/Public dwX As Integer
    private/Public dwY As Integer
    private/Public dwXSize As Integer
    private/Public dwYSize As Integer
    private/Public dwXCountChars As Integer
    private/Public dwYCountChars As Integer
    private/Public dwFillAttribute As Integer
    private/Public dwFlags As Integer
    private/Public wShowWindow As Short
    private/Public cbReserved2 As Short
    private/Public lpReserved2 As Integer
    private/Public hStdInput As Integer
    private/Public hStdOutput As Integer
    private/Public hStdError As Integer

End Structure

Private/Public Function CreateProcessWithLogonW( _

  """<MarshalAs(UnmanagedType.LPWStr)>""" ByVal lpUsername As String, _
  """<MarshalAs(UnmanagedType.LPWStr)>""" ByVal lpDomain As String, _
  """<MarshalAs(UnmanagedType.LPWStr)>""" ByVal lpPassword As String, _
  ByVal dwLogonFlags As Integer, _
  """ByVal lpApplicationName As Integer""", _
  """<MarshalAs(UnmanagedType.LPWStr)>""" ByVal lpCommandLine As String, _
  ByVal dwCreationFlags As Integer, _
  """ByVal lpEnvironment As Integer""", _
  """<MarshalAs(UnmanagedType.LPWStr)>""" ByVal lpCurrentDirectory As String, _
  ByRef lpStartupInfo As STARTUPINFO, _
  ByRef lpProcessInformation As PROCESS_INFORMATION _
  ) As Integer
End Function

"Sample Code"

Private/Public Const LOGON_WITH_PROFILE = &H1

Private/Public/private Const CREATE_DEFAULT_ERROR_MODE = &H4000000

""" Before using this, you will need to change the STARTUPINFO and PROCESS_ INFORMATION STRUCTURE

Private/Public Declare Function CloseHandle Lib "kernel32.dll" (ByVal hObject As Long) As Long

Private/Public Shared Function OpenAppAsUser(<MarshalAs(UnmanagedType.LPWStr)> byVal UserName As String, _

<MarshalAs(UnmanagedType.LPWStr)> ByVal Password As String, _

<MarshalAs(UnmanagedType.LPWStr)> ByVal DomainName As String, _

<MarshalAs(UnmanagedType.LPWStr)> ByVal ApplicationName As String, _

<MarshalAs(UnmanagedType.LPWStr)> ByVal CommandLine As String, _

<MarshalAs(UnmanagedType.LPWStr)> ByVal CurrentDirectory As String) As Long

Dim si As STARTUPINFO

Dim pi As PROCESS_INFORMATION

Dim Result As Long

si.cb = Len(si)

Result = CreateProcessWithLogonW(UserName, DomainName, Password, LOGON_WITH_PROFILE, 0%, CommandLine, CREATE_DEFAULT_ERROR_MODE, 0%, CurrentDirectory, si, pi)

    ' CreateProcessWithLogonW() does not

If Result <> 0 Then

    CloseHandle(pi.hThread)
    CloseHandle(pi.hProcess)
    W2KRunAsUser = 0

Else

    W2KRunAsUser = Err.LastDllError
    MsgBox("CreateProcessWithLogonW() failed with error " & Err.LastDllError, vbExclamation)

End If

End Function

VB Signature:

' This Code Does not work in VB.Net

C# Signature:

[DllImport("advapi32.dll", SetLastError=true, CharSet=CharSet.Unicode)]

public static extern bool CreateProcessWithLogonW(

    String userName,
    String domain,
    String password,
    UInt32 logonFlags,
    String applicationName,
    String commandLine,
    UInt32 creationFlags,
    UInt32 environment,
    String currentDirectory,
    ref   StartupInfo startupInfo,
    out  ProcessInformation processInformation);

User-Defined Types:

STARTUPINFO, PROCESS_INFORMATION

Notes:

Tips & Tricks:

Please add some!

Sample Code:

using System;

using System.Runtime.InteropServices;

//Chris Hand cj_hand@hotmail.com

//2005.03.13

namespace RunAs

{

    class Class1
    {
        public const UInt32 Infinite = 0xffffffff;
        public const Int32      Startf_UseStdHandles = 0x00000100;
        public const Int32      StdOutputHandle = -11;
        public const Int32      StdErrorHandle = -12;

        [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)]
        public struct StartupInfo
        {
            public int    cb;
            public String reserved;
            public String desktop;
            public String title;
            public int    x;
            public int    y;
            public int    xSize;
            public int    ySize;
            public int    xCountChars;
            public int    yCountChars;
            public int    fillAttribute;
            public int    flags;
            public UInt16 showWindow;
            public UInt16 reserved2;
            public byte   reserved3;
            public IntPtr stdInput;
            public IntPtr stdOutput;
            public IntPtr stfError;
        }

        internal struct ProcessInformation
        {
            public IntPtr process;
            public IntPtr thread;
            public int    processId;
            public int    threadId;
        }

        [DllImport("advapi32.dll", SetLastError=true, CharSet=CharSet.Unicode)]
        public static extern bool CreateProcessWithLogonW(
            String userName,
            String domain,
            String password,
            UInt32 logonFlags,
            String applicationName,
            String commandLine,
            UInt32 creationFlags,
            UInt32 environment,
            String currentDirectory,
            ref   StartupInfo startupInfo,
            out  ProcessInformation processInformation);

        [DllImport("kernel32.dll", SetLastError=true)]
        public static extern bool GetExitCodeProcess(IntPtr process, ref UInt32 exitCode);

        [DllImport("Kernel32.dll", SetLastError=true)]
        public static extern UInt32 WaitForSingleObject(IntPtr handle, UInt32 milliseconds);

        [DllImport("Kernel32.dll", SetLastError=true)]
        public static extern IntPtr GetStdHandle(IntPtr handle);

        [DllImport("Kernel32.dll", SetLastError=true)]
        public static extern bool CloseHandle(IntPtr handle);

        [STAThread]
        static void Main(string[] args)
        {
            StartupInfo startupInfo = new StartupInfo();
            startupInfo.reserved = null;
            startupInfo.flags &= Startf_UseStdHandles;
            startupInfo.stdOutput = (IntPtr)StdOutputHandle;
            startupInfo.stdError = (IntPtr)StdErrorHandle;

            UInt32 exitCode = 123456;
            ProcessInformation processInfo = new ProcessInformation();

            String command = @"c:\windows\notepad.exe";
            String user    = "administrator";
            String domain  = System.Environment.MachineName;
            String password = "Blank";
            String currentDirectory = System.IO.Directory.GetCurrentDirectory();

            try
            {
                CreateProcessWithLogonW(
                    user,
                    domain,
                    password,
                    (UInt32) 1,
                    command,
                    command,
                    (UInt32) 0,
                    (UInt32) 0,
                    currentDirectory,
                    ref startupInfo,
                    out processInfo);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }

            Console.WriteLine("Running ...");
            WaitForSingleObject(processInfo.process, Infinite);
            GetExitCodeProcess(processInfo.process, ref exitCode);

            Console.WriteLine("Exit code: {0}", exitCode);

            CloseHandle(processInfo.process);
            CloseHandle(processInfo.thread);
        }
    }

}

Alternative Managed API:

System.Diagnostics.Process

Documentation

Please edit this page!

Do you have...

  • helpful tips or sample code to share for using this API in managed code?
  • corrections to the existing content?
  • variations of the signature you want to share?
  • additional languages you want to include?

Select "Edit This Page" on the right hand toolbar and edit it! Or add new pages containing supporting types needed for this API (structures, delegates, and more).

 
Access PInvoke.net directly from VS:
Terms of Use
Find References
Show Printable Version
Revisions