Einzelnen Beitrag anzeigen

TiGü

Registriert seit: 6. Apr 2011
Ort: Berlin
3.070 Beiträge
 
Delphi 10.4 Sydney
 
#3

AW: CommandLineInterpreter aufrufen und Daten übermitteln

  Alt 9. Aug 2022, 10:29
Immer ein bisschen gucken und mitdenken wenn man Quelltexte von Stack Overflow kopiert.
So funktioniert das:

Delphi-Quellcode:
function ExecuteBatch(const ABatch: TStringList): Boolean;

    procedure LWritePipeOut(OutputPipe: THandle; InString: AnsiString);
    var
        byteswritten: DWORD;
    begin
        InString := InString + sLineBreak;
        WriteFile(OutputPipe, InString[1], Length(InString), byteswritten, nil);
    end;

var
    i: Integer;
    LCLI: AnsiString;
    LSecurityAttribute: TSecurityAttributes;
    LProcessInformation: TProcessInformation;
    LStartUpInfo: TStartupInfoA;
    NewStdIn, WriteStdIn: THandle;
begin
    Result := False;

    LCLI := GetEnvironmentVariable('COMSPEC');
    UniqueString(LCLI);

    LSecurityAttribute.nlength := SizeOf(TSecurityAttributes);
    LSecurityAttribute.binherithandle := True;
    LSecurityAttribute.lpsecuritydescriptor := nil;
    CreatePipe(NewStdIn, WriteStdIn, @LSecurityAttribute, 0);

    FillChar(LStartUpInfo, Sizeof(LStartUpInfo), #0);
    LStartUpInfo.hStdInput := NewStdIn;
    LStartUpInfo.dwFlags := STARTF_USESTDHANDLES + STARTF_USESHOWWINDOW;
    LStartUpInfo.wShowWindow := SW_Show;
    LStartUpInfo.cb := SizeOf(LStartUpInfo);
    LStartUpInfo.lpTitle := PAnsiChar('Batch Console');

    if CreateProcessA(nil, PAnsiChar(LCLI), @LSecurityAttribute, @LSecurityAttribute, True,
        CREATE_NEW_CONSOLE or SYNCHRONIZE,
        nil, nil, LStartUpInfo, LProcessInformation) then
    begin
        for i := 0 to Pred(ABatch.Count) do
        begin
            LWritePipeOut(WriteStdIn, PChar(ABatch.Strings[i]));
        end;
        CloseHandle(LProcessInformation.hProcess);
        CloseHandle(LProcessInformation.hThread);
        Result := True
    end;

    CloseHandle(NewStdIn);
    CloseHandle(WriteStdIn);
end;

procedure TForm1.Button1Click(Sender: TObject);
var
    sl: TStringlist;
begin
    sl := TStringlist.create;
    sl.Add('ping 127.0.0.1');
    sl.Add('ping 8.8.8.8');
    if ExecuteBatch(sl) then
    begin
        Caption := 'fertig';
    end;
    sl.Free;
end;
  Mit Zitat antworten Zitat