在C++中,调用::CreateProcess
来启动Windows可执行文件需要以下步骤:
- 包含必要的头文件:#include<windows.h>
#include <tchar.h>
#include<iostream>
- 定义主函数并初始化参数:int main()
{
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
ZeroMemory(&pi, sizeof(pi));
- 设置要启动的可执行文件的路径和命令行参数: TCHAR szCmdline[] = _T("C:\\path\\to\\executable.exe arg1 arg2");
- 设置进程的安全属性: si.dwFlags = STARTF_USESHOWWINDOW;
si.wShowWindow = SW_SHOW;
- 调用
::CreateProcess
函数来启动进程: if (!::CreateProcess(NULL,
szCmdline,
NULL,
NULL,
FALSE,
0,
NULL,
NULL,
&si,
&pi))
{
std::cout << "CreateProcess failed (" << ::GetLastError() << ")."<< std::endl;
return 0;
} - 等待进程完成并关闭句柄: ::WaitForSingleObject(pi.hProcess, INFINITE);
DWORD dwExitCode = 0;
::GetExitCodeProcess(pi.hProcess, &dwExitCode);
::CloseHandle(pi.hProcess);
::CloseHandle(pi.hThread);
std::cout << "Process exited with code " << dwExitCode << "."<< std::endl;
return 0;
}
这样,你就可以在C++中使用::CreateProcess
函数来启动Windows可执行文件了。