Wednesday, February 8, 2012

Wait on a process launched by ShellExecute

I recently found myself needing to launch a process via ShellExecute() (for certain reasons, it needed to be ShellExecute() vs. CreateProcess() or some other method) and wait on the process launched to exit before proceeding with the calling thread.

I found references to suggesting using ShellExecuteEx(). Here's the source code example of how to do this:

 // This will launch the lpFile and wait for it to exit
 memset(&info, 0, sizeof(SHELLEXECUTEINFO));
 info.cbSize = sizeof(SHELLEXECUTEINFO);
 info.lpVerb = L"open";
 info.lpFile = "foo.exe";
 info.nShow = SW_SHOWNORMAL;


 // Wait until child process exits.
 WaitForSingleObject(info.hProcess, INFINITE);

Note that you are responsible for closing the handle since using the SEE_MASK_NOCLOSEPROCESS flag tells ShellExecuteEx() to leave the handle open.

No comments:

Post a Comment