delphi执行外部程序并等待结束返回响应

//写成函数  需要引用 ShellAPI 单元;

function ExecuteFileWait(ExecuteFile:string):Integer;    //实现执行外部程序,并等待程序结束的函数,返回值为1
 var
  SEInfo: TShellExecuteInfo;
  ExitCode: DWORD;
  ParamString, StartInString: string;
begin
  FillChar(SEInfo, SizeOf(SEInfo), #0);
  SEInfo.cbSize := SizeOf(TShellExecuteInfo);
  with SEInfo do begin
    fMask := SEE_MASK_NOCLOSEPROCESS;
    Wnd := Application.Handle;
    lpFile := PChar(ExecuteFile);
    nShow := SW_SHOWNORMAL;
  end;
  if ShellExecuteEx(@SEInfo) then
  begin
    repeat
      Application.ProcessMessages;
      GetExitCodeProcess(SEInfo.hProcess, ExitCode);
      if ExitCode = STILL_ACTIVE then Sleep(100);
    until (ExitCode <> STILL_ACTIVE) or Application.Terminated;
     Result :=1; //已结束,返回值1
  end
  else
    Result := -1;
end;

procedure TForm1.Button2Click(Sender: TObject);  //调用
begin
    ExecuteFileWait('calc.exe');
    ShowMessage('OK! 程序已退出!');
end;

 

posted @ 2023-05-10 14:59  williamlv  阅读(278)  评论(0编辑  收藏  举报