How to wait for ShellExecute to run?

buddy123 picture buddy123 · Jul 14, 2013 · Viewed 40.5k times · Source

I have manages to use ShellExecute in VC++ in order to launch a document. Now I wish to run a command-line tool that receives some arguments, and to run in the background (as hidden, not minimized) and let it block my program flow, so that i'll be able to wait for it to finish. How to i alter the command-line of:

ShellExecute(NULL,"open",FULL_PATH_TO_CMD_LINE_TOOL,ARGUMENTS,NULL,SW_HIDE);

The problem is, I have tool that converts html to pdf, and I wish that once the tool finished, aka pdf is ready, to have another ShellExecute to view it.

Answer

Roger Rowland picture Roger Rowland · Jul 14, 2013

There is a CodeProject article that shows how, by using ShellExecuteEx instead of ShellExecute:

SHELLEXECUTEINFO ShExecInfo = {0};
ShExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);
ShExecInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
ShExecInfo.hwnd = NULL;
ShExecInfo.lpVerb = NULL;
ShExecInfo.lpFile = "c:\\MyProgram.exe";        
ShExecInfo.lpParameters = "";   
ShExecInfo.lpDirectory = NULL;
ShExecInfo.nShow = SW_SHOW;
ShExecInfo.hInstApp = NULL; 
ShellExecuteEx(&ShExecInfo);
WaitForSingleObject(ShExecInfo.hProcess, INFINITE);
CloseHandle(ShExecInfo.hProcess);

The crucial point is the flag SEE_MASK_NOCLOSEPROCESS, which, as MSDN says

Use to indicate that the hProcess member receives the process handle. This handle is typically used to allow an application to find out when a process created with ShellExecuteEx terminates

Also, note that:

The calling application is responsible for closing the handle when it is no longer needed.