CreateProcess (kernel32)
Last changed: -83.249.236.115

.
Summary
Creates a new process and its primary thread.

C# Signature:

[DllImport("kernel32.dll")]
static extern bool CreateProcess(string lpApplicationName,
   string lpCommandLine, ref SECURITY_ATTRIBUTES lpProcessAttributes,
   ref SECURITY_ATTRIBUTES lpThreadAttributes, bool bInheritHandles,
   uint dwCreationFlags, IntPtr lpEnvironment, string lpCurrentDirectory,
   [In] ref STARTUPINFO lpStartupInfo,
   out PROCESS_INFORMATION lpProcessInformation);

User-Defined Types:

STARTUPINFO, PROCESS_INFORMATION, SECURITY_ATTRIBUTES

Notes:

This is great for starting an external app and then use the PID and handle for calls to functions such as WaitForSingleObject and all window message functions.

Tips & Tricks:

Add this in constructor of a class to logically treat the app as an object.

Sample Code:

public static void StartupNotepad()
{
     const uint NORMAL_PRIORITY_CLASS = 0x0020;

     bool retValue;
     string Application = Environment.GetEnvironmentVariable("windir") + @"\Notepad.exe";
     string CommandLine = @" c:\boot.ini";
     PROCESS_INFORMATION pInfo = new PROCESS_INFORMATION();
     STARTUPINFO sInfo = new STARTUPINFO();
     SECURITY_ATTRIBUTES pSec = new SECURITY_ATTRIBUTES();
     SECURITY_ATTRIBUTES tSec = new SECURITY_ATTRIBUTES();
     pSec.nLength = Marshal.SizeOf(pSec);
     tSec.nLength = Marshal.SizeOf(tSec);

     //Open Notepad
     retValue = CreateProcess(Application,CommandLine,
     ref pSec,ref tSec,false,NORMAL_PRIORITY_CLASS,
     IntPtr.Zero,null,ref sInfo,out pInfo);

     Console.WriteLine("Process ID (PID): " + pInfo.dwProcessId);
     Console.WriteLine("Process Handle : " + pInfo.hProcess);
}

Alternative Managed API:

System.Diagnostics.Process.Start

Documentation