I'm making an app that allows me to "control" the lifespan of an executable.
I have an app with a TStringList
that has the address of several executable files (.exe
). I would like to be able to launch them whenever I want, I already do this with ShellExecute()
, but I don't know how I could close them when they are running.
ShellExecute()
does not return anything that can be used to control the launched process.
If you use ShellExecuteEx()
instead, you can specify the SEE_MASK_NOCLOSEPROCESS
flag, and then grab the SHELLEXECUTEINFO.hProcess
field after launch. You can then use GetProcessId()
on that handle to get the process id.
But, it would be better to use CreateProcess()
instead, and grab the returned PROCESS_INFORMATION.dwProcessId
and PROCESS_INFORMATION.hProcess
fields.
Given the process id, you can then use EnumWindows()
and GetWindowThreadProcessId()
to find all of the top-level windows that belong to the process, and then you can send a WM_CLOSE
or WM_QUIT
message to each window. You can then use WaitForSingleObject()
, or GetExitCodeProcess()
in a loop, to monitor the process handle until the process exits or a timeout elapses.
If the process does not exit in a reasonable amount of time, then given the process handle, you can use TerminateProcess()
to brute-force it.