static extern bool CreateProcess( string lpApplicationName, string lpCommandLine, ref SecurityAttributes lpProcessAttributes, ref SecurityAttributes lpThreadAttributes, bool bInheritHandles, uint dwCreationFlags, IntPtr lpEnvironment, string lpCurrentDirectory, [In] ref StartupInfoEx lpStartupInfo, out ProcessInfomration lpProcessInformation );
// Internal methods /////////////////////// static string RunUnderParent(string executable, string arguments, int parentProcessId) { var pInfo = new ProcessInfomration(); var sInfoEx = new StartupInfoEx(); sInfoEx.StartupInfo.cb = Marshal.SizeOf(sInfoEx); var lpValue = IntPtr.Zero; try { var lpSize = IntPtr.Zero; var success = InitializeProcThreadAttributeList(IntPtr.Zero, 1, 0, ref lpSize); if (success || lpSize == IntPtr.Zero) { return($"could not get process thread attribute list size"); } sInfoEx.lpAttributeList = Marshal.AllocHGlobal(lpSize); success = InitializeProcThreadAttributeList(sInfoEx.lpAttributeList, 1, 0, ref lpSize); if (!success) { return($"error in InitializeProcThreadAttributeList: {Marshal.GetLastWin32Error()}"); } var parentHandle = Process.GetProcessById(parentProcessId).Handle; lpValue = Marshal.AllocHGlobal(IntPtr.Size); Marshal.WriteIntPtr(lpValue, parentHandle); success = UpdateProcThreadAttribute( sInfoEx.lpAttributeList, 0, (IntPtr)PROC_THREAD_ATTRIBUTE_PARENT_PROCESS, lpValue, (IntPtr)IntPtr.Size, IntPtr.Zero, IntPtr.Zero); if (!success) { return($"error in UpdateProcThreadAttribute: {Marshal.GetLastWin32Error()}"); } var pSec = new SecurityAttributes(); var tSec = new SecurityAttributes(); pSec.nLength = Marshal.SizeOf(pSec); tSec.nLength = Marshal.SizeOf(tSec); success = CreateProcess( executable, " " + arguments, ref pSec, ref tSec, false, EXTENDED_STARTUPINFO_PRESENT, IntPtr.Zero, null, ref sInfoEx, out pInfo ); if (!success) { return($"error in CreateProcess: {Marshal.GetLastWin32Error()}"); } return(null); } finally { if (sInfoEx.lpAttributeList != IntPtr.Zero) { DeleteProcThreadAttributeList(sInfoEx.lpAttributeList); Marshal.FreeHGlobal(sInfoEx.lpAttributeList); } Marshal.FreeHGlobal(lpValue); if (pInfo.hProcess != IntPtr.Zero) { CloseHandle(pInfo.hProcess); } if (pInfo.hThread != IntPtr.Zero) { CloseHandle(pInfo.hThread); } } }