Reputation: 543
I want to launching a sub application from the main application using CreateProcess
function with the following steps:
.exe
program from the main without window for the sub programrand Sleep
In the following my example code for the above but the sub program running with window(in this case NotePad) and i can't terminate the sub program.
#include "stdafx.h"
#include <windows.h>
#include <conio.h>
#include <strsafe.h>
#include <direct.h>
#include <string.h>
int main(int argc, char* argv[])
{
HWND hWnd;
STARTUPINFO sInfo;
PROCESS_INFORMATION pInfo;
ZeroMemory(&sInfo, sizeof(sInfo));
sInfo.cb = sizeof(sInfo);
ZeroMemory(&pInfo, sizeof(pInfo));
if (CreateProcess("C:\\WINDOWS\\System32\\notepad.exe", NULL, NULL, NULL, false, CREATE_NO_WINDOW, NULL, NULL, &sInfo, &pInfo))
{
printf("Sleeping 100ms...\n");
Sleep(100);
DWORD dwExitCode;
GetExitCodeProcess(pInfo.hProcess, &dwExitCode);
CloseHandle(pInfo.hThread);
CloseHandle(pInfo.hProcess);
}
system("pause");
return 0;
}
Upvotes: 2
Views: 9303
Reputation: 61910
The reason the notepad window shows is because it's not a console application. MSDN says this about CREATE_NO_WINDOW
:
The process is a console application that is being run without a console window. Therefore, the console handle for the application is not set. This flag is ignored if the application is not a console application, or if it is used with either CREATE_NEW_CONSOLE or DETACHED_PROCESS.
Instead, use the STARTUPINFO
you pass in:
sInfo.dwFlags = STARTF_USESHOWWINDOW;
sInfo.wShowWindow = SW_HIDE;
I believe that will affect the last argument to WinMain
in Notepad's main function, but I'm not sure.
As for why notepad doesn't close, GetExitCodeProcess
doesn't actually end the process, it just retrieves the state. You can use TerminateProcess
instead:
TerminateProcess(pInfo.hProcess, 0);
Upvotes: 2