Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CreateProcessWithTokenW - Example of usage in C#

Tags:

c#

winapi

I'm trying to use the CreateProcessWithTokenW() win32 API function to start a new process with a token. The problem is that I'm quite new to the win32 API and I have no idea how to use the function properly, and which structs etc. that are needed. Could someone provide me with an example of how to use the function correctly in C#?

like image 678
user1049697 Avatar asked Nov 16 '11 17:11

user1049697


1 Answers

This is unmanaged code so you need to use P/Invoke (Platform Invoke), here's the function signature for CreateProcessWithTokenW():

[DllImport("advapi32", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern bool CreateProcessWithTokenW(
    IntPtr hToken, 
    LogonFlags dwLogonFlags, 
    string lpApplicationName, 
    string lpCommandLine, 
    CreationFlags dwCreationFlags, 
    IntPtr lpEnvironment, 
    string lpCurrentDirectory, 
    [In] ref STARTUPINFO lpStartupInfo, 
    out PROCESS_INFORMATION lpProcessInformation);

You can use an enum like this to pass in the LogonFlags param (to keep the .net feeling :) ) :

public enum LogonFlags
{
     WithProfile = 1,
     NetCredentialsOnly
}

Here's the enum for the CreationFlags following the documentation available here :

public enum CreationFlags
{
    DefaultErrorMode = 0x04000000,
    NewConsole = 0x00000010,
    NewProcessGroup = 0x00000200,
    SeparateWOWVDM = 0x00000800,
    Suspended = 0x00000004,
    UnicodeEnvironment = 0x00000400,
    ExtendedStartupInfoPresent = 0x00080000
}
like image 192
Nasreddine Avatar answered Oct 30 '22 23:10

Nasreddine