how do i get shellexecute to work?

Thread Solved

Join Date: Oct 2009
Posts: 11
Reputation: Vdub.za is an unknown quantity at this point 
Solved Threads: 0
Vdub.za Vdub.za is offline Offline
Newbie Poster

how do i get shellexecute to work?

 
0
  #1
Oct 16th, 2009
Hi there,

Me and a buddy are having trouble in getting shellexecute to work in delphi 7. No matter what permetation of the word shellexecute i use, when i want to run the app shellexecute is not recognized. so how do i get shellexecute to work. been trying to get it to open an exe on my hdd. say something like winamp just to test it out.

Can anybody please help us with this.

Thank you in advance,
Vdub.za
Reply With Quote Quick reply to this message  
Join Date: Feb 2009
Posts: 3,212
Reputation: sknake has much to be proud of sknake has much to be proud of sknake has much to be proud of sknake has much to be proud of sknake has much to be proud of sknake has much to be proud of sknake has much to be proud of sknake has much to be proud of sknake has much to be proud of sknake has much to be proud of 
Solved Threads: 572
Sponsor
sknake's Avatar
sknake sknake is offline Offline
.NET Enthusiast
 
0
  #2
Oct 16th, 2009
Here is d6 code demonstrating how to call shell execute:
Pascal and Delphi Syntax (Toggle Plain Text)
  1. procedure TMainFm.Button1Click(Sender: TObject);
  2. Var
  3. p: PChar;
  4. begin
  5. p := 'C:\file path\appname.exe';
  6. ShellExecute(
  7. 0,
  8. 'open',
  9. p,
  10. nil,
  11. nil,
  12. SW_SHOW);
  13. end;

You also need to add ShellApi to the uses statement for the unit.
Scott Knake
Custom Software Development
Apex Software, Inc.
Reply With Quote Quick reply to this message  
Join Date: Oct 2009
Posts: 11
Reputation: Vdub.za is an unknown quantity at this point 
Solved Threads: 0
Vdub.za Vdub.za is offline Offline
Newbie Poster
 
0
  #3
Oct 22nd, 2009
Hi

I tried it, but is stopped at VAR and reported procedure expected, but variable found. doesnt want to run. what did i do wrong?
Reply With Quote Quick reply to this message  
Join Date: May 2009
Posts: 1
Reputation: gcaramia is an unknown quantity at this point 
Solved Threads: 1
gcaramia gcaramia is offline Offline
Newbie Poster
 
0
  #4
Oct 24th, 2009
Originally Posted by Vdub.za View Post
Hi

I tried it, but is stopped at VAR and reported procedure expected, but variable found. doesnt want to run. what did i do wrong?
try:
Pascal and Delphi Syntax (Toggle Plain Text)
  1. procedure TMainFm.Button1Click(Sender: TObject);
  2. Var p : string;
  3. begin
  4. p := 'C:\file path\appname.exe';
  5. ShellExecute(0,'open',pchar(p),nil,nil,SW_SHOWNORMAL);
  6. end;

Gianni
Reply With Quote Quick reply to this message  
Join Date: Oct 2009
Posts: 11
Reputation: Vdub.za is an unknown quantity at this point 
Solved Threads: 0
Vdub.za Vdub.za is offline Offline
Newbie Poster

Yeah BABY!

 
0
  #5
33 Days Ago
Hello,


I Just want to say thanks alot for your help on this one. it really helped me alot and now i can continue working on my app. Thanks so much for everything . You just made my day.

Regards
Vdub.za
Reply With Quote Quick reply to this message  
Join Date: Nov 2009
Posts: 40
Reputation: BitFarmer is an unknown quantity at this point 
Solved Threads: 3
BitFarmer BitFarmer is offline Offline
Light Poster
 
0
  #6
18 Days Ago
There is a very good unit called Launch.pas out there in the net, i grabbed it time ago and have added more functions over the time (not in the authors initial text, sorry), like one to wait until some exe drop below 1%CPU usage.

I copy it here so you can add to your app if useful:

Pascal and Delphi Syntax (Toggle Plain Text)
  1. {************************************************************************}
  2. {* *}
  3. {* file : Launch.PAS *}
  4. {* *}
  5. {* type : unit *}
  6. {* *}
  7. {* location : \QUIRT\SRC\DELPHI *}
  8. {* *}
  9. {* purpose : Launch external programs *}
  10. {* *}
  11. {* author : Lennert Ploeger (NKI / AVL) *}
  12. {* *}
  13. {* date : 19980325 *}
  14. {* *}
  15. {* portability: 32 bit delphi only (V2.0 up) *}
  16. {* *}
  17. {* notes : None *}
  18. {* *}
  19. {************************************************************************}
  20. {* Updates:
  21. When Who What
  22. 19980325 lsp Created
  23. 19980331 lsp Search for programs in PATH using SearchPath()
  24. 19980609 lsp Allow white-spaces for the program to launch
  25. 19980709 lsp Allow 'prog' to be empty in StartProgram
  26. 19980731 lsp Enclose both file and directory names in double quotes
  27. 19980901 lsp Removed some obsolete functions
  28. 19981004 mvh Added RunProgram (waits until ready)
  29. 19981005 mvh Renamed to RunProgramBlocking (waits until ready)
  30. 19981020 lsp Program launched in RunProgramBlocking() is started
  31.   minimized and not given focus
  32. 19990110 mvh RunProgramBlocking returns value
  33. 19990111 lsp Fixed comment about CloseHandle()
  34. 19990112 mvh Added RunProgramWaiting, shortened code by reuse
  35. 19990425 lsp FileUtil -> QFileUtil
  36. 19990609 lsp Removed QFileUtil dependency
  37. *}
  38.  
  39. unit Launch;
  40.  
  41. interface
  42.  
  43. //Para pasar de ProcId a THandle
  44. type
  45. TWindowRec = record
  46. Handle: THandle;
  47. ProcessId: Cardinal;
  48. WindowName: PChar;
  49. end;
  50. PWindowRec = ^TWindowRec;
  51.  
  52. function LocateProgramInSearchPath(ProgramName: string): string;
  53. procedure StartProgram(prog, workdir: string; params: array of string);
  54. function RunProgramBlocking(prog, workdir: string; params: array of string): integer;
  55. function RunFileBlocking(fichero: string): boolean;
  56. function RunProgramWaiting(prog, workdir: string; params: array of string): integer;
  57. function ProgramStarter(prog, workdir: string; params: array of string; showmode: integer): integer;
  58. //HCSoft...
  59. //Localizar Handler de un proceso a partir del filename del ejecutable
  60. function GetProcHandle(ExeFileName: string): THandle;
  61. //Hacer cosas a partir del THandle...
  62. function KillProc(H: THandle): boolean;
  63. function WaitProcIddle(H: THandle; MinSeg: double = 1; MaxSeg: double = 30): double;
  64. //Hacer cosas a partir del FileName...
  65. function WaitExeIddle(ExeFileName: string; MinSeg: double = 0.1; MaxSeg: double = 10): double;
  66. function KillTask(ExeFileName: string): boolean;
  67.  
  68. implementation
  69.  
  70. uses
  71. SysUtils, Dialogs, Windows, Forms, FileCtrl, ShellAPI, HCBase, Tlhelp32;
  72.  
  73.  
  74. // Routine to retrieve file information using a file/dirname
  75. function FileDirNameWin32FindData(FullPathName: string; var Win32FindData: TWin32FindData): boolean;
  76. var
  77. Handle: THandle;
  78. begin
  79. Handle := FindFirstFile(PChar(FullPathName), Win32FindData);
  80. if Handle <> INVALID_HANDLE_VALUE then
  81. begin
  82. Windows.FindClose(Handle);
  83. Result := True;
  84. end
  85. else
  86. Result := False;
  87. end;
  88.  
  89. // Search for 'ProgramName' in %PATH% using Win API function 'SearchPath'
  90. function LocateProgramInSearchPath(ProgramName: string): string;
  91. type
  92. BufType = array[0..255] of char;
  93. var
  94. SPPath: BufType;
  95. PathPtr: PChar;
  96. begin
  97. if SearchPath(nil, PChar(ProgramName), nil, 255, SPPath, PathPtr)>0 then
  98. Result := StrPas(SPPath)
  99. else
  100. Result := ProgramName;
  101. end;
  102.  
  103. function TestExistence(const Name: string): boolean;
  104. begin
  105. Result := FileExists(Name) or DirectoryExists(Name);
  106. end;
  107.  
  108. // Internal common code for the 3 exported program starters
  109.  
  110. function ProgramStarter(prog, workdir: string;
  111. params: array of string; showmode: integer): integer;
  112. var
  113. StartInf : TStartupInfo;
  114. ProcInf : TProcessInformation;
  115. args : string;
  116. progtmp : string;
  117. pAppName : PChar;
  118. pworkdir : PChar;
  119. i : integer;
  120. begin
  121. // It appears that it is also possible to call ShellExecute, what seems
  122. // to be a bit a higher level function:
  123. // ShellExecute(handle, "open", path_to_file, NULL, NULL, SW_SHOWNORMAL);
  124. // Another alternative can be calling WinExec, but with the drawback of
  125. // not having the possibility to specify the work directory.
  126.  
  127. ZeroMemory(@StartInf, sizeof(TStartupInfo));
  128. ZeroMemory(@ProcInf, sizeof(TProcessInformation));
  129. StartInf.cb := sizeof(TStartupInfo);
  130. StartInf.dwFlags := STARTF_USESHOWWINDOW ;
  131. StartInf.wShowWindow := showmode;
  132.  
  133. // To call CreateProcess() we should be carefull to enclose files
  134. // passed in 'lpCommandLine' in double quotes ('"') to make sure that
  135. // it understands where one starts and ends. The pecularity is that the
  136. // name of the executable should NOT be enclosed in double quotes. Passing
  137. // both the file and the arguments in lpCommandLine and leaving
  138. // lpApplicationName empty is no option, since the application and
  139. // arguments should be white-space delimited that way.
  140.  
  141. progtmp := prog;
  142. if not FileExists(progtmp) then
  143. progtmp := LocateProgramInSearchPath(progtmp);
  144.  
  145. if Length(prog)>0 then
  146. args := '"' + prog + '"';
  147. for i:=low(params) to high(params) do
  148. begin
  149. // Enclose file and directory names in double quotes to get them seperated properly
  150. if TestExistence(params[i]) then
  151. begin
  152. if Length(args)>0 then // Try to add spaces only when necessary
  153. args := args + ' "' + params[i] + '"'
  154. else
  155. args := '"' + params[i] + '"'
  156. end
  157. else if Length(params[i])>0 then
  158. begin
  159. if Length(args)>0 then // Try to add spaces only when necessary
  160. args := args + ' ' + params[i]
  161. else
  162. args := params[i];
  163. end;
  164. end;
  165.  
  166. if Length(workdir)>0 then
  167. pworkdir := PChar(workdir)
  168. else
  169. pworkdir := nil;
  170.  
  171. if Length(progtmp)>0 then
  172. pAppName := PChar(progtmp)
  173. else
  174. pAppName := nil;
  175.  
  176. if not CreateProcess(pAppName, PChar(args), nil, nil, False, 0, nil,
  177. pworkdir, StartInf, ProcInf) then
  178. MessageDlg('El programa ' + prog + ' no ha podido ser ejecutado', mtError, [mbOk], 0);
  179.  
  180. // The handles for both the process and the main thread must be closed through
  181. // calls to CloseHandle. These handles are not needed, so it is best to close
  182. // them immediately after the process is created.
  183. result := ProcInf.hProcess;
  184. CloseHandle(ProcInf.hThread);
  185. end;
  186.  
  187. // routine to start program 'prog' using the file-parameters in 'params'.
  188. // Be carefull with passing [] for the params, since the stackpointer seems
  189. // to get corrupt. However, starting a program with no arguments can be done
  190. // using StartProgram(program, workdir, [ ' ' ]).
  191. procedure StartProgram(prog, workdir: string; params: array of string);
  192. var
  193. hProcess: integer;
  194. begin
  195. hProcess := ProgramStarter(prog, workdir, params, SW_SHOWDEFAULT);
  196. CloseHandle(hProcess);
  197. end;
  198.  
  199. // routine to run program 'prog' using the file-parameters in 'params'.
  200. // and wait until it is finished
  201. // Be careful with passing [] for the params, since the stackpointer seems
  202. // to get corrupt. However, starting a program with no arguments can be done
  203. // using StartProgram(program, workdir, [ ' ' ]).
  204. function RunProgramBlocking(prog, workdir: string; params: array of string): integer;
  205. var
  206. hProcess: integer;
  207. j : Cardinal;
  208. begin
  209. hProcess := ProgramStarter(prog, workdir, params, SW_SHOWMINNOACTIVE);
  210.  
  211. WaitForSingleObject(hProcess, INFINITE);
  212. GetExitCodeProcess(hProcess, j);
  213. result := integer(j);
  214.  
  215. CloseHandle(hProcess);
  216. end;
  217.  
  218. function RunFileBlocking(fichero: string): boolean;
  219. var
  220. SEI: TShellExecuteInfo;
  221. begin
  222. //Ejecuto el fichero con el programa adecuado...
  223. FillChar(SEI, SizeOf(SEI), 0); // Wipe the record to start with
  224. Result:= true;
  225. with SEI do
  226. begin
  227. cbSize := SizeOf(SEI);
  228. fMask := see_Mask_NoCloseProcess;
  229. Wnd := Application.MainForm.Handle;
  230. lpVerb := 'open';
  231. lpFile := PAnsiChar(fichero);
  232. lpDirectory := PChar(ExtractFilePath(fichero));
  233. nShow := sw_ShowNormal;
  234. if not ShellExecuteEx(@SEI) then
  235. Result:= False;
  236. end;
  237. //Espero a que liberen el fichero...
  238.  
  239. //WaitForSingleObjet no se debe usar si se va a abrir una ventana porque
  240. //el proceso que llama deja de procesar mensajes y la ventana nueva cuelga:
  241. //http://msdn.microsoft.com/en-us/library/ms687032%28VS.85%29.aspx
  242. while WaitForSingleObject(SEI.hProcess, 100) = WAIT_TIMEOUT do
  243. Application.ProcessMessages;
  244. end;
  245.  
  246. // routine to run program 'prog' using the file-parameters in 'params'.
  247. // and wait until it is finished. During the wait, however, messages are
  248. // processed so that the user interface remains 'live'.
  249. function RunProgramWaiting(prog, workdir: string; params: array of string): integer;
  250. var
  251. hProcess: integer;
  252. j : Cardinal;
  253. begin
  254. hProcess := ProgramStarter(prog, workdir, params, SW_SHOWMINNOACTIVE);
  255. while WaitForSingleObject(hProcess, 10) = WAIT_TIMEOUT do
  256. Application.ProcessMessages;
  257. GetExitCodeProcess(hProcess, j);
  258. result := integer(j);
  259. CloseHandle(hProcess);
  260. end;
  261.  
  262.  
  263. // **************************************************************************
  264. // ** AÑADIDO SERGIO PARA MENEJAR PROCESOS POR SU HANDLE O SU EXE FILENAME **
  265. // **************************************************************************
  266.  
  267. function FileTime2Milliseconds(FileTime: TFileTime): integer;
  268. var ST: TSystemTime;
  269. begin
  270. FileTimeToSystemTime(FileTime, ST);
  271. result:= ST.wMilliseconds + 1000 *
  272. (ST.wSecond + 60 * (ST.wMinute + 60 * ST.wHour)) ;
  273. end;
  274.  
  275. //Sabemos 'WINWORD.EXE', dame un THandle del proceso para hacerle putadillas
  276. function GetProcHandle(ExeFileName: string): THandle;
  277. var
  278. ContinueLoop: BOOL;
  279. FSnapshotHandle: THandle;
  280. FProcessEntry32: TProcessEntry32;
  281. begin
  282. result:= 0;
  283. FSnapshotHandle:= CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
  284. FProcessEntry32.dwSize:= Sizeof(FProcessEntry32);
  285. ContinueLoop:= Process32First(FSnapshotHandle, FProcessEntry32);
  286. while integer(ContinueLoop) <> 0 do begin
  287. if ((UpperCase(ExtractFileName(FProcessEntry32.szExeFile)) = UpperCase(ExeFileName))
  288. or (UpperCase(FProcessEntry32.szExeFile) = UpperCase(ExeFileName))) then begin
  289. result:= OpenProcess(PROCESS_ALL_ACCESS, FALSE, FProcessEntry32.th32ProcessID);
  290. break;
  291. end;
  292. ContinueLoop:= Process32Next(FSnapshotHandle, FProcessEntry32);
  293. end;
  294. CloseHandle(FSnapshotHandle);
  295. end;
  296.  
  297. //Mata este proceso!
  298. function KillProc(H: THandle): boolean;
  299. const PROCESS_TERMINATE=$0001;
  300. begin
  301. result:= (Integer(TerminateProcess(H, 0))<>0);
  302. end;
  303.  
  304. //Espera a que un Proceso use menos del 1% de la CPU.
  305. //Si no encuentra el proceso, esperara MinSeg, y si lo encuentra pero no baja
  306. //del 1%, se esperara un maximo de MaxSeg.
  307. function WaitProcIddle(H: THandle; MinSeg: double = 1; MaxSeg: double = 30): double;
  308. var
  309. LastProcTime, NewProcTime, UsedTime: integer; //Milisegundos todo
  310. CreaTime, ExitTime, UserTime, KernelTime: TFileTime;
  311. const
  312. WAIT_FOR_MS: integer = 1000; //Cada 1 segundo (1000 ms) vuelves a mirar
  313. IDDLE_LOWER: integer = 5; //Usados < 5 ms = (%CPU<0.5) salimos
  314. begin
  315. //Llevo esperando 0 segundos...
  316. result:= 0;
  317. //Igual no lo encuentro...
  318. if (H=0) then begin
  319. //Pues no esta, espero algo y me voy...
  320. sleep(round(MinSeg*1000));
  321. end else begin
  322. //Proceso encontrado, a esperar...
  323. if GetProcessTimes(H, CreaTime, ExitTime, KernelTime, UserTime)=BOOL(0) then exit;
  324. LastProcTime:= FileTime2Milliseconds(KernelTime) + FileTime2Milliseconds(UserTime);
  325. //Cada decima de segundo, recalculo...
  326. repeat
  327. sleep(WAIT_FOR_MS);
  328. result:= result + (WAIT_FOR_MS/1000);
  329. //Rescato tiempo dle proceso actualizado...
  330. if GetProcessTimes(H, CreaTime, ExitTime, KernelTime, UserTime)=BOOL(0) then exit;
  331. NewProcTime:= FileTime2Milliseconds(KernelTime) + FileTime2Milliseconds(UserTime);
  332. UsedTime:= (NewProcTime - LastProcTime);
  333. if (UsedTime) < IDDLE_LOWER then
  334. break;
  335. LastProcTime:= NewProcTime;
  336. until (result >= MaxSeg);
  337. end;
  338. end;
  339.  
  340. // ***************************************************
  341. // ** MANEJO PROCESOS SABIENDO SU NOMBRE DE FICHERO **
  342. // ***************************************************
  343.  
  344. //Espera a que una tarea baje del 1%CPU usando su filename
  345. function WaitExeIddle(ExeFileName: string; MinSeg: double = 0.1; MaxSeg: double = 10): double;
  346. begin
  347. result:= WaitProcIddle(GetProcHandle(ExeFileName), MinSeg, MaxSeg);
  348. end;
  349.  
  350. //Mata programa por su nombre...
  351. function KillTask(ExeFileName: string): boolean;
  352. begin
  353. result:= KillProc(GetProcHandle(ExeFileName));
  354. end;
  355.  
  356. end.
Reply With Quote Quick reply to this message  
Reply

This thread has been marked solved.
Perhaps start a new thread instead?
Message:



Similar Threads
Other Threads in the Pascal and Delphi Forum
Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC