为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

C++
一只名叫tom的猫 2019-12-26 10:50:43
寻找一个例子:启动一个EXE等待EXE完成。可执行文件完成后,正确关闭所有句柄。
查看完整描述

3 回答

?
慕少森

TA贡献2019条经验 获得超9个赞

像这样:


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);

}


查看完整回答
反对 回复 2019-12-26
?
神不在的星期二

TA贡献1963条经验 获得超6个赞

如果您的应用程序是Windows GUI应用程序,则使用下面的代码进行等待不是理想的选择,因为将不会处理您应用程序的消息。对于用户来说,您的应用程序似乎已挂起。


WaitForSingleObject(&processInfo.hProcess, INFINITE)

类似于下面未经测试的代码可能会更好,因为它将继续处理Windows消息队列,并且您的应用程序将保持响应状态:


//-- wait for the process to finish

while (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);

      }

    }

  }

}


查看完整回答
反对 回复 2019-12-26
  • 3 回答
  • 0 关注
  • 687 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信