如何在C ++中调用:: CreateProcess来启动Windows可执行文件?

寻找一个例子:

  1. 启动一个EXE

  2. 等待EXE完成。

  3. 可执行文件完成后,正确关闭所有句柄。


一只名叫tom的猫
浏览 690回答 3
3回答

慕少森

像这样:STARTUPINFO info={sizeof(info)};PROCESS_INFORMATION processInfo;if (CreateProcess(path, cmd, NULL, NULL, TRUE, 0, NULL, NULL, &info, &processInfo)){    WaitForSingleObject(processInfo.hProcess, INFINITE);    CloseHandle(processInfo.hProcess);    CloseHandle(processInfo.hThread);}

神不在的星期二

如果您的应用程序是Windows GUI应用程序,则使用下面的代码进行等待不是理想的选择,因为将不会处理您应用程序的消息。对于用户来说,您的应用程序似乎已挂起。WaitForSingleObject(&processInfo.hProcess, INFINITE)类似于下面未经测试的代码可能会更好,因为它将继续处理Windows消息队列,并且您的应用程序将保持响应状态://-- wait for the process to finishwhile (true){  //-- see if the task has terminated  DWORD dwExitCode = WaitForSingleObject(ProcessInfo.hProcess, 0);  if (   (dwExitCode == WAIT_FAILED   )      || (dwExitCode == WAIT_OBJECT_0 )      || (dwExitCode == WAIT_ABANDONED) )  {    DWORD dwExitCode;    //-- get the process exit code    GetExitCodeProcess(ProcessInfo.hProcess, &dwExitCode);    //-- the task has ended so close the handle    CloseHandle(ProcessInfo.hThread);    CloseHandle(ProcessInfo.hProcess);    //-- save the exit code    lExitCode = dwExitCode;    return;  }  else  {    //-- see if there are any message that need to be processed    while (PeekMessage(&message.msg, 0, 0, 0, PM_NOREMOVE))    {      if (message.msg.message == WM_QUIT)      {        return;      }      //-- process the message queue      if (GetMessage(&message.msg, 0, 0, 0))      {        //-- process the message        TranslateMessage(&pMessage->msg);        DispatchMessage(&pMessage->msg);      }    }  }}
打开App,查看更多内容
随时随地看视频慕课网APP