Author: Radikal Q3
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
1 2 procedure TForm1.Button1Click(Sender: TObject);
3 4 procedure RunAndWaitShell(Ejecutable,
5 Argumentos:string6 ;Visibilidad:integer);
7 var8 Info:TShellExecuteInfo;
9 pInfo:PShellExecuteInfo;
10 exitCode:DWord;
11 begin12 {Puntero a Info}13 {Pointer to Info}14 pInfo:=@Info;
15 {Rellenamos Info}16 {Fill info}17 with Info do18 begin19 cbSize:=SizeOf(Info);
20 fMask:=SEE_MASK_NOCLOSEPROCESS;
21 wnd:=Handle;
22 lpVerb:=nil;
23 lpFile:=PChar(Ejecutable);
24 {Parametros al ejecutable}25 {Executable parameters}26 lpParameters:=Pchar(Argumentos+#0);
27 lpDirectory:=nil;
28 nShow:=Visibilidad;
29 hInstApp:=0;
30 end;
31 {Ejecutamos}32 {Execute}33 ShellExecuteEx(pInfo);
34 35 {Esperamos que termine}36 {Wait to finish}37 repeat38 exitCode := WaitForSingleObject(Info.hProcess,500);
39 Application.ProcessMessages;
40 until (exitCode <> WAIT_TIMEOUT);
41 end;
42 43 begin44 RunAndWaitShell('c:\windows\notepad.exe','c:\autoexec.bat',Sw_ShowNormal);
45 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:
46 47 RunAndWaitShell('c:\discoc\tools\q.exe', 'c:\autoexec.bat', Sw_ShowNormal);