Somewhere in my application, I am creating a process like this:
STARTUPINFO startupInfo;
ZeroMemory(&startupInfo, sizeof(startupInfo));
startupInfo.cb = sizeof(STARTUPINFO);
PROCESS_INFORMATION processInfo;
ZeroMemory(&processInfo, sizeof(processInfo));
const auto created = CreateProcessW(
pathToExe,
cmdLine,
nullptr,
nullptr,
false,
CREATE_NEW_CONSOLE,
nullptr,
workingDir,
&startupInfo,
&processInfo);
The exe I am running here is a console application.
At some later time, I would like to gracefully stop that process. I can kill it with TerminateProcess
, but I would like to make it more graceful, as the process might have to save data to some database or perform some clean up (e.g. close hardware connections).
I tried to get the process HWND
without success with EnumWindows
and GetWindowThreadProcessId
. In fact, EnumWindows
doesn't list the process I created. With that HWND
, my idea was to send a WM_CLOSE
message.
Maybe I should not use the CREATE_NEW_CONSOLE
flag? I tried the following startup info:
STARTUPINFO startupInfo;
ZeroMemory(&startupInfo, sizeof(startupInfo));
startupInfo.cb = sizeof(STARTUPINFO);
si.dwFlags = STARTF_USESHOWWINDOW;
si.wShowWindow = SW_SHOW;
but that does not show me a console window (which I need to have). What am I doing wrong? How should I create my process and how can I then later gracefully stop it?
CodePudding user response:
In fact, at the time where I was trying to gracefully kill my console, it was too early to get a HWND
to the console window. It was in a test where I naively just created the process and then almost straightaway killed it. If I wait long enough (i.e. if I actually interact for some time with the process I created), then I can get the handle to the console window and send it a WM_CLOSE
message with success.