我正在编写一些代码来恢复备份。为此,我使用外部程序。用户可以选择多个文件,我将为for
循环内的每个文件执行外部程序。在恢复下一个文件之前,如何暂停程序直到外部程序退出?
答案 0 :(得分:0)
这是一个使用CreateProcess()和WaitForSingleObject()
的示例procedure RunaAndWait(Command:String);
var
fStartupInfo: TStartupInfo;
fProcessInformation: TProcessInformation;
fProgram: String;
begin
fProgram := trim(Command);
FillChar(fStartupInfo, SizeOf(fStartupInfo), 0);
with fStartupInfo do
begin
cb := SizeOf(TStartupInfo);
wShowWindow := SW_HIDE;
end;
if CreateProcess(nil, pchar(fProgram), nil, nil, true, CREATE_NO_WINDOW,
nil, nil, fStartupInfo, fProcessInformation) then
begin
while WaitForSingleObject(fProcessInformation.hProcess, 10) > 0 do
begin
Application.ProcessMessages;
end;
CloseHandle(fProcessInformation.hProcess);
CloseHandle(fProcessInformation.hThread);
end
else
begin
RaiseLastOSError;
end;
end;
用法:
procedure TForm1.Button1Click(Sender: TObject);
begin
RunaAndWait('notepad.exe');
Showmessage('Finished');
end;