CreateProcess
以下函数封装了使用 CreateProcess
Windows API 启动其他程序的代码。
它是可配置的,可以等到调用进程完成或立即返回。
参数:
FileName
- 可执行文件的完整路径Params
- 命令行参数或使用空字符串Folder
- 被调用程序的工作文件夹 - 如果从FileName
中提取空路径WaitUntilTerminated
- 如果 true 函数将等待进程完成执行WaitUntilIdle
- 如果 true 函数将调用 WaitForInputIdle 函数并等待指定的进程完成处理其初始输入,直到没有用户输入挂起RunMinimized
- 如果真正的过程将最小化运行ErrorCode
- 如果函数失败,则会包含遇到的 Windows 错误代码
function ExecuteProcess(const FileName, Params: string; Folder: string; WaitUntilTerminated, WaitUntilIdle, RunMinimized: boolean;
var ErrorCode: integer): boolean;
var
CmdLine: string;
WorkingDirP: PChar;
StartupInfo: TStartupInfo;
ProcessInfo: TProcessInformation;
begin
Result := true;
CmdLine := '"' + FileName + '" ' + Params;
if Folder = '' then Folder := ExcludeTrailingPathDelimiter(ExtractFilePath(FileName));
ZeroMemory(@StartupInfo, SizeOf(StartupInfo));
StartupInfo.cb := SizeOf(StartupInfo);
if RunMinimized then
begin
StartupInfo.dwFlags := STARTF_USESHOWWINDOW;
StartupInfo.wShowWindow := SW_SHOWMINIMIZED;
end;
if Folder <> '' then WorkingDirP := PChar(Folder)
else WorkingDirP := nil;
if not CreateProcess(nil, PChar(CmdLine), nil, nil, false, 0, nil, WorkingDirP, StartupInfo, ProcessInfo) then
begin
Result := false;
ErrorCode := GetLastError;
exit;
end;
with ProcessInfo do
begin
CloseHandle(hThread);
if WaitUntilIdle then WaitForInputIdle(hProcess, INFINITE);
if WaitUntilTerminated then
repeat
Application.ProcessMessages;
until MsgWaitForMultipleObjects(1, hProcess, false, INFINITE, QS_ALLINPUT) <> WAIT_OBJECT_0 + 1;
CloseHandle(hProcess);
end;
end;
使用上述功能
var
FileName, Parameters, WorkingFolder: string;
Error: integer;
OK: boolean;
begin
FileName := 'C:\FullPath\myapp.exe';
WorkingFolder := ''; // if empty function will extract path from FileName
Parameters := '-p'; // can be empty
OK := ExecuteProcess(FileName, Parameters, WorkingFolder, false, false, false, Error);
if not OK then ShowMessage('Error: ' + IntToStr(Error));
end;