C++启动一个进程

时间:2021-08-19 19:47:51

调用CreateProcess

STARTUPINFO si;
PROCESS_INFORMATION pi;
si.dwFlags = STARTF_USESHOWWINDOW;
si.wShowWindow = SW_SHOWNORMAL;
ZeroMemory( &si, sizeof(si) );
si.cb = sizeof(si);
ZeroMemory( &pi, sizeof(pi) );
if(!CreateProcess(NULL, (LPTSTR)(LPCTSTR) sExeFilePathAndName,NULL,NULL,FALSE,CREATE_NEW_CONSOLE,NULL,NULL,&si, &pi ))
{
AfxMessageBox("自动升级程序AutoUPDATe.Exe文件不存在或损坏!");
return FALSE;
}
CloseHandle(pi.hThread); // 关闭子进程的主线程句柄
WaitForSingleObject(pi.hProcess, INFINITE); // 等待子进程的退出
// 获取子进程的退出码
DWORD dwExitCode;
GetExitCodeProcess(pi.hProcess, &dwExitCode);
CloseHandle(pi.hProcess); //关闭子进程句柄

调用ShellExecute

ShellExecute(NULL,"open","EXE路径",NULL,NULL,SW_SHOW);

SHELLEXECUTEINFO ShExecInfo = {0};
ShExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);
ShExecInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
ShExecInfo.hwnd = NULL;
ShExecInfo.lpVerb = NULL;
ShExecInfo.lpFile = strExe;
ShExecInfo.lpParameters = sParams;
ShExecInfo.lpDirectory = NULL;
ShExecInfo.nShow = SW_HIDE;
ShExecInfo.hInstApp = NULL;
BOOL ret = ShellExecuteEx(&ShExecInfo);
WaitForSingleObject(ShExecInfo.hProcess,INFINITE);