2010-03-14 52 views
4

我有蝙蝠文件,這使得一些操作。如何從Delphi運行此文件並等待,直到停止。 類似的東西:德爾福:等到蝙蝠腳本運行到底

procedure TForm1.Button1Click(Sender: TObject); 
begin 
//Starting bat-file 
bla-bla-bla 
showmessage('Done'); 
end; 

回答

5

這執行給定的命令行,並等待通過命令行啓動退出程序。如果程序返回零退出代碼,則返回true;如果程序未啓動或返回非零錯誤代碼,則返回false。

function ExecAndWait(const CommandLine: string) : Boolean; 
var 
    StartupInfo: Windows.TStartupInfo;  // start-up info passed to process 
    ProcessInfo: Windows.TProcessInformation; // info about the process 
    ProcessExitCode: Windows.DWord;   // process's exit code 
begin 
    // Set default error result 
    Result := False; 
    // Initialise startup info structure to 0, and record length 
    FillChar(StartupInfo, SizeOf(StartupInfo), 0); 
    StartupInfo.cb := SizeOf(StartupInfo); 
    // Execute application commandline 
    if Windows.CreateProcess(nil, PChar(CommandLine), 
    nil, nil, False, 0, nil, nil, 
    StartupInfo, ProcessInfo) then 
    begin 
    try 
     // Now wait for application to complete 
     if Windows.WaitForSingleObject(ProcessInfo.hProcess, INFINITE) 
     = WAIT_OBJECT_0 then 
     // It's completed - get its exit code 
     if Windows.GetExitCodeProcess(ProcessInfo.hProcess, 
      ProcessExitCode) then 
      // Check exit code is zero => successful completion 
      if ProcessExitCode = 0 then 
      Result := True; 
    finally 
     // Tidy up 
     Windows.CloseHandle(ProcessInfo.hProcess); 
     Windows.CloseHandle(ProcessInfo.hThread); 
    end; 
    end; 
end; 

來源:http://www.delphidabbler.com/codesnip?action=named&showsrc=1&routines=ExecAndWait

+4

缺少關鍵點(批處理命令文件需要通過''C'開關將它們作爲參數傳遞給'cmd.exe'來執行)。 – mghie 2010-03-14 21:53:14

2

下面是一些代碼,例如 - 在Windows 7工作正常,是無形的

(funcion ExeAndWait是借的)。

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。如果你喜歡,你可以在運行時使用TStringList類構建批處理文件。