Delphi: wait until bat-script runs to the end

前端 未结 2 1998

I have bat-file, that make some operations. How to run this file from Delphi and wait, until it stops. Something like that:

procedure TForm1.Button1Click(Se         


        
2条回答
  •  礼貌的吻别
    2021-01-13 15:55

    Here is some code and example - under Windows 7 works fine and is invisible

    (funcion ExeAndWait is borrowed).

    function ExeAndWait(ExeNameAndParams: string; ncmdShow: Integer = SW_SHOWNORMAL): Integer;
    var
        StartupInfo: TStartupInfo;
        ProcessInformation: TProcessInformation;
        Res: Bool;
        lpExitCode: DWORD;
    begin
        with StartupInfo do //you can play with this structure
        begin
            cb := SizeOf(TStartupInfo);
            lpReserved := nil;
            lpDesktop := nil;
            lpTitle := nil;
            dwFlags := STARTF_USESHOWWINDOW;
            wShowWindow := ncmdShow;
            cbReserved2 := 0;
            lpReserved2 := nil;
        end;
        Res := CreateProcess(nil, PChar(ExeNameAndParams), nil, nil, True,
            CREATE_DEFAULT_ERROR_MODE
            or NORMAL_PRIORITY_CLASS, nil, nil, StartupInfo, ProcessInformation);
        while True do
        begin
            GetExitCodeProcess(ProcessInformation.hProcess, lpExitCode);
            if lpExitCode <> STILL_ACTIVE then
                Break;
            Application.ProcessMessages;
        end;
        Result := Integer(lpExitCode);
    end;
    
    procedure TForm1.Button1Click(Sender: TObject);
    begin
        ExeAndWait(ExtractFilePath(Application.ExeName) + 'test.bat', SW_HIDE);
        ShowMessage('Done!');
    end;
    

    PS. If you like you can build batch file at runtime using TStringList class.

提交回复
热议问题