title: Using Process.Start() to start a process as a different user from within a Windows Service
body: <p>I'd like to periodically run an arbitrary .NET exe under a specified user account from a Windows Service. </p>
  
  <p>So far I've got my windows service running with logic to decide what the target process is, and when to run it.
  The target process is started in the following manner:</p>
  
  <ol>
  <li>The Windows Service is started using "administrator" credentials.</li>
  <li>When the time comes, an intermediate .NET process is executed with arguments detailing which process should be started (filename, username, domain, password).</li>
  <li>This process creates a new System.Diagnostics.Process, associates a ProcessStartInfo object filled with the arguments passed to it, and then calls Start() on the process object.</li>
  </ol>
  
  <p>The <strong>first time</strong> this happens, <strong>the target process executes fine and then closes normally</strong>. Every subsequent time however, as soon as the target process is started it throws the error "Application failed to initalize properly (0xc0000142)". Restarting the Windows Service will allow the process to run successfully once again (for the first execution).</p>
  
  <p>Naturally, the goal is to have target process execute successfully every time.</p>
  
  <p>Regarding step 2 above: To run a process as a different user .NET calls the win32 function CreateProcessWithLogonW. This function requires a window handle to log the specified user in. Since the Windows Service isn't running in Interactive Mode it has no window handle. This intermediate process solves the issue, as it has a window handle which can be passed to the target process.</p>
  
  <p>Please, no suggestions of using psexec or the windows task planner. I've accepted my lot in life, and that includes solving the problem in the manner stated above.</p>