[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);
<DllImport("kernel32.dll")> _
Shared Function CreateProcess(lpApplicationName As String, _
lpCommandLine As String, ByRef lpProcessAttributes As SECURITY_ATTRIBUTES, _
ByRef lpThreadAttributes As SECURITY_ATTRIBUTES,bInheritHandles As Boolean, _
dwCreationFlags As Uint, lpEnvironment As IntPtr, lpCurrentDirectory As String, _
<[In]> ByRef lpStartupInfo As STARTUPINFO, _
<[Out]> ByRef lpProcessInformation As PROCESS_INFORMATION) As Boolean
STARTUPINFO, PROCESS_INFORMATION, SECURITY_ATTRIBUTES
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.
It should also be considered when wanting to start a process without all the diagnostic capability. When starting a process, about 3 MB of DLLs are loaded as well as several extra threads started. Doing this via Win32 API avoids this overhead.
Add this in constructor of a class to logically treat the app as an object.
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);
}
System.Diagnostics.Process.Start