2017年9月7日 星期四

執行外部程式 ShellExecuteEx

uses ShellAPI;

procedure pr_ShellExecuteEx(AFileName, AParam:String; AWaiting:Boolean=False);
var
  SEInfo: TShellExecuteInfo;
  ExitCode: DWORD;
  ExecuteFile, ParamString, StartInString: string;
begin
  ExecuteFile := AFileName;
  ParamString := AParam;
  FillChar(SEInfo, SizeOf(SEInfo), 0) ;
  SEInfo.cbSize := SizeOf(TShellExecuteInfo) ;
  with SEInfo do begin
    fMask := SEE_MASK_NOCLOSEPROCESS;
    Wnd := Application.Handle;
    lpFile := PChar(ExecuteFile) ;
    //Exp: ParamString can contain the application parameters.
    lpParameters := PChar(ParamString) ;
    //Exp: StartInString specifies the name of the working directory. If ommited, the current directory is used.
    //lpDirectory := PChar(StartInString) ;
    nShow := SW_SHOWNORMAL;
  end;
  if ShellExecuteEx(@SEInfo) then begin
    repeat
      //等待程式關閉後, 釋回控制權
      if AWaiting then
        WaitForSingleObject(SEInfo.hProcess, INFINITE);
      //
      Application.ProcessMessages;
      GetExitCodeProcess(SEInfo.hProcess, ExitCode) ;
    until (ExitCode <> STILL_ACTIVE) or
    Application.Terminated;
  end;
end;

2 則留言: