1

I am using following function to launch a particular exe. I need to wait for this process to complete before moving onto next set of code. How do i wait for the process to complete?

[DllImport("advapi32.dll", EntryPoint = "CreateProcessAsUser", SetLastError = true, CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
extern static Boolean CreateProcessAsUser(IntPtr hToken, String lpApplicationName, String lpCommandLine, ref SECURITY_ATTRIBUTES lpProcessAttributes,
        ref SECURITY_ATTRIBUTES lpThreadAttributes, Boolean bInheritHandle, Int32 dwCreationFlags, IntPtr lpEnvironment,
        String lpCurrentDirectory, ref STARTUPINFO lpStartupInfo, out PROCESS_INFORMATION lpProcessInformation);
Eve
  • 212
  • 5
  • 18

1 Answers1

3

The PROCESS_INFORMATION struct you get back from the method also contains the handle of the created process and its ID. So you could for example do this:

Process.GetProcessById(procInfo.dwProcessId).WaitForExit()

However, note that if the process terminates before you get to this call, it could be remotely possible you'd get a different process instead. So it would be better to do some validation, just in case:

var process = Process.GetProcessById(procInfo.dwProcessId);

if (process.Handle == procInfo.hProcess)
  process.WaitForExit();

// The process has definitely exited by now

However, you don't have to use CreateProcessAsUser at all. You can use a Process.Start overload that allows you to specify username and password - this should be the preferred way to start a process under a diferent user in C#. You can also use ProcessStartInfo to specify a username and password.

Luaan
  • 62,244
  • 7
  • 97
  • 116