Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I wait until an external process has completed?

Tags:

winapi

delphi

So I have made a form in Delphi that allows me to run various sikuli scripts with various configurations. What I am working on now is to make it possible for someone using the form, to set up various sikuli scripts to run on after another. As in:

Step 1: SikuliScript1 with ConfigFile1. Step 2: SikuliScript2 with ConfigFile2. etc... This is my code so far:

procedure TSikRunForm.btnRunClick(Sender: TObject);
begin
    DirCombo:= '/C '+DirSik+'\sikuli-script.cmd' +' -r ' + DirScript + ' --args '+DirConfig;
    if SikFound then begin
      ShellExecute(Handle, nil, 'cmd.exe', pChar(DirCombo), nil, SW_SHOWNORMAL);
      Application.minimize;
    end else begin
      ShowMessage('Select the correct folder for your Sikuli installation folder');
    end;
end;

And this works perfect, the sikuli script runs perfectly, and while running, the cmd line is visible with the various actions shown that are being performed. After the sikuli script is done, the cmd line closes on its own. So the shell handler knows when to shut down the running process. So my question is: Is it possible to tell delphi: After the handler has shut the process, run the next process (Sikuli Script)? Now I know I can go with the whole createProcess in delphi, but it just seems overkill. There has got to be a way to do this faster and easier. Anyone have a clue?

like image 813
user2524670 Avatar asked Jun 27 '13 06:06

user2524670


1 Answers

With CreateProcess you can get a process handle and with WaitForSingleObject you can check when the process is complete. I use the following function, this runs the command in the background:

procedure ExecuteAndWait(const aCommando: string);
var
  tmpStartupInfo: TStartupInfo;
  tmpProcessInformation: TProcessInformation;
  tmpProgram: String;
begin
  tmpProgram := trim(aCommando);
  FillChar(tmpStartupInfo, SizeOf(tmpStartupInfo), 0);
  with tmpStartupInfo do
  begin
    cb := SizeOf(TStartupInfo);
    wShowWindow := SW_HIDE;
  end;

  if CreateProcess(nil, pchar(tmpProgram), nil, nil, true, CREATE_NO_WINDOW,
    nil, nil, tmpStartupInfo, tmpProcessInformation) then
  begin
    // loop every 10 ms
    while WaitForSingleObject(tmpProcessInformation.hProcess, 10) > 0 do
    begin
      Application.ProcessMessages;
    end;
    CloseHandle(tmpProcessInformation.hProcess);
    CloseHandle(tmpProcessInformation.hThread);
  end
  else
  begin
    RaiseLastOSError;
  end;
end;
like image 153
Bart van Dijk Avatar answered Sep 16 '22 14:09

Bart van Dijk