Execute a file by its extension and wait to finish (Views: 709)
Problem/Question/Abstract: Execute/open any file with the associated application, waiting until it finish. Answer: We will make it thanks to the function of the API ShellExecuteEx Here the code is: Add 'ShellApi' in the uses of your form procedure TForm1.Button1Click(Sender: TObject); procedure RunAndWaitShell(Ejecutable, Argumentos:string ;Visibilidad:integer); var Info:TShellExecuteInfo; pInfo:PShellExecuteInfo; exitCode:DWord; begin {Puntero a Info} {Pointer to Info} pInfo:=@Info; {Rellenamos Info} {Fill info} with Info do begin cbSize:=SizeOf(Info); fMask:=SEE_MASK_NOCLOSEPROCESS; wnd:=Handle; lpVerb:=nil; lpFile:=PChar(Ejecutable); {Parametros al ejecutable} {Executable parameters} lpParameters:=Pchar(Argumentos+#0); lpDirectory:=nil; nShow:=Visibilidad; hInstApp:=0; end; {Ejecutamos} {Execute} ShellExecuteEx(pInfo); {Esperamos que termine} {Wait to finish} repeat exitCode := WaitForSingleObject(Info.hProcess,500); Application.ProcessMessages; until (exitCode <> WAIT_TIMEOUT); end; begin RunAndWaitShell('c:\windows\notepad.exe','c:\autoexec.bat',Sw_ShowNormal); end; If we call to an executable, this it will be executed. If we call to a non executable file, the function will execute its associate application. For example, to open a file HTML with the default browser of the system: RunAndWaitShell('c:\kk\registro.html', '', Sw_ShowNormal); We can also execute and wait to finish a DOS program. For example, this opens my DOS editor QEdit to edit the Autoexec.bat: RunAndWaitShell('c:\discoc\tools\q.exe', 'c:\autoexec.bat', Sw_ShowNormal); |