Mega Code Archive

 
Categories / Delphi / Examples
 

Execute a document and wait for it to finish

Title: execute a document and wait for it to finish? { This tip allows you to open any document with its associated application (not only exe, com) and wait for it to finish. } { Dieser Tip erm glicht es, nicht nur normale Programme, sondern auch Dateien, die mit Programmen ge ffnet werden, auszuf hren und darauf zu warten, bis sie beendet sind. } uses Shellapi; function StartAssociatedExe(FileName: string; var ErrorCode: Cardinal): Boolean; var Prg: string; ProcessInfo: TProcessInformation; StartupInfo: TStartupInfo; begin SetLength(Prg, MAX_PATH); Result := False; ErrorCode := FindExecutable(PChar(FileName), nil, PChar(Prg)); if ErrorCode = 32 then begin SetLength(Prg, StrLen(PChar(Prg))); FillChar(StartupInfo, SizeOf(TStartupInfo), 0); with StartupInfo do begin cb := SizeOf(TStartupInfo); wShowWindow := SW_SHOW; end; if CreateProcess(PChar(Prg), PChar(Format('%s %s', [Prg, FileName])), nil, nil, False, NORMAL_PRIORITY_CLASS, nil, nil, StartupInfo, ProcessInfo) then begin WaitForSingleObject(ProcessInfo.hProcess, INFINITE); GetExitCodeProcess(ProcessInfo.hProcess, ErrorCode); CloseHandle(ProcessInfo.hProcess); CloseHandle(ProcessInfo.hThread); Result := True; end else ErrorCode := GetLastError; end; end; // Example, Beispiel: procedure TForm1.Button1Click(Sender: TObject); var ErrorCode: Cardinal; begin StartAssociatedExe('c:\test.doc', ErrorCode); end;