How to get an output of an Exec'ed program in Inno Setup?

前端 未结 2 965
旧时难觅i
旧时难觅i 2020-11-27 05:49

Is it possible to get an output of an Exec\'ed executable?

I want to show the user an info query page, but show the default value of MAC address in the

相关标签:
2条回答
  • 2020-11-27 06:23

    I had to do the same (execute command line calls and get the result) and came up with a more general solution.

    It also fixes strange bugs if quoted paths are used in the actual calls by using the /S flag for cmd.exe.

    { Exec with output stored in result. }
    { ResultString will only be altered if True is returned. }
    function ExecWithResult(const Filename, Params, WorkingDir: String; const ShowCmd: Integer;
      const Wait: TExecWait; var ResultCode: Integer; var ResultString: String): Boolean;
    var
      TempFilename: String;
      Command: String;
    begin
      TempFilename := ExpandConstant('{tmp}\~execwithresult.txt');
      { Exec via cmd and redirect output to file. Must use special string-behavior to work. }
      Command :=
        Format('"%s" /S /C ""%s" %s > "%s""', [
          ExpandConstant('{cmd}'), Filename, Params, TempFilename]);
      Result := Exec(ExpandConstant('{cmd}'), Command, WorkingDir, ShowCmd, Wait, ResultCode);
      if not Result then
        Exit;
      LoadStringFromFile(TempFilename, ResultString);  { Cannot fail }
      DeleteFile(TempFilename);
      { Remove new-line at the end }
      if (Length(ResultString) >= 2) and (ResultString[Length(ResultString) - 1] = #13) and
         (ResultString[Length(ResultString)] = #10) then
        Delete(ResultString, Length(ResultString) - 1, 2);
    end;
    

    Usage:

    Success :=
      ExecWithResult('ipconfig', '/all', '', SW_HIDE, ewWaitUntilTerminated,
        ResultCode, ExecStdout) or
      (ResultCode <> 0);
    

    The result can also be loaded into a TStringList object to get all lines:

    Lines := TStringList.Create;
    Lines.Text := ExecStdout;
    { ... some code ... }
    Lines.Free;
    
    0 讨论(0)
  • 2020-11-27 06:29

    Yes, use redirection of the standard output to a file:

    [Code]
    
    function NextButtonClick(CurPage: Integer): Boolean;
    var
      TmpFileName, ExecStdout: string;
      ResultCode: integer;
    begin
      if CurPage = wpWelcome then begin
        TmpFileName := ExpandConstant('{tmp}') + '\ipconfig_results.txt';
        Exec('cmd.exe', '/C ipconfig /ALL > "' + TmpFileName + '"', '', SW_HIDE,
          ewWaitUntilTerminated, ResultCode);
        if LoadStringFromFile(TmpFileName, ExecStdout) then begin
          MsgBox(ExecStdout, mbInformation, MB_OK);
          { do something with contents of file... }
        end;
        DeleteFile(TmpFileName);
      end;
      Result := True;
    end;
    

    Note that there may be more than one network adapter, and consequently several MAC addresses to choose from.

    0 讨论(0)
提交回复
热议问题