I have the following code sample:
#include <iostream>
#include <windows.h>
#include <string>
using namespace std;
void main()
{
SHELLEXECUTEINFO ShExecInfo = { 0 };
ShExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);
ShExecInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
ShExecInfo.hwnd = NULL;
ShExecInfo.lpVerb = NULL;
ShExecInfo.lpFile = "cmd.exe";
ShExecInfo.lpParameters = "";
ShExecInfo.lpDirectory = NULL;
ShExecInfo.nShow = SW_SHOW;
ShExecInfo.hInstApp = NULL;
ShellExecuteEx(&ShExecInfo);
WaitForSingleObject(ShExecInfo.hProcess, INFINITE);
std::cout << "hi! Im done!";
system("pause");
}
When I try the code running cmd.exe, the message isn't printed to the screen until I closed the cmd.exe window.
However, when I try the code running calc.exe instead, the message is printed to the screen before the calculator process ends.
Why are these two executables exhibiting different behaviors?
I think I missed something with my understanding of the WaitForSingleObject() function.
I tried your code on Windows 10, and SysInternals Process Monitor shows the following:

As you can see, calc.exe spawns a new process and then ends, thus satisfying the wait. That is why you see your output immediately. This second process is the actual calculator process. In my case, it is located at this path:
C:\Program Files\WindowsApps\Microsoft.WindowsCalculator_10.1612.3341.0_x64__8wekyb3d8bbwe\Calculator.exe
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With