1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
| Function RunSpyStdOut(Const Commande:String; Var Out:String): Integer;
Var
Start : TStartupInfo ;
Process : TProcessInformation;
Sa : TSecurityAttributes;
PipeOut,
PipeIn ,
Readed : Cardinal;
Buffer : String ;
WhatApen: DWord;
begin
RunSpyStdOut := -1;
// Choix de la taille du Buffer...
SetLength(Buffer, SPipe);
// Initialisation des attributs de sécurité
FillChar (Sa, SizeOf(Sa), #0);
Sa.nLength := SizeOf (Sa);
Sa.bInheritHandle := TRUE;
// Création du Pipe
if not CreatePipe(PipeIn, PipeOut, @Sa, SPipe) then
Exit;
// Paramétrage du lancemant de l'application
FillChar(Start,SizeOf(Start),#0);
Start.cb := SizeOf(Start);
Start.dwFlags := STARTF_USESTDHANDLES Or STARTF_USESHOWWINDOW;
Start.hStdOutput := PipeOut;
Start.wShowWindow := SW_HIDE;
// Création du Processus pour l'application
If not CreateProcess(Nil,
PChar(Commande),
Nil, Nil,
True,
0, Nil, Nil,
Start,Process) Then Begin
CloseHandle(Pipein);
CloseHandle(PipeOut);
Exit;
End;
// OK...
// On peut, et on doit, fermer le handle d'écriture du pipe.
// 1 - Parceque de toute façon on ne va rien écrire dedans.
// 2 - Parceque si non la fontion ReadFile risque de rester bloquer car un
// Handle est toujours ouvert à la fermeture de l'pplication dont on
// récupaire la sortie standard.
CloseHandle (PipeOut);
Repeat
// Quoi qu'il se passe, on va lire le flux du pipe car, s'il est plein,
// la fonction d'écriture de la console dans le pipe ne rend pas la main
// au programme apellant.
// Si le pipe est plein, le programme ne reprend jamais la main !!!
ReadFile(PipeIn, Buffer[1], SPipe, Readed, nil);
Out:=Out+copy(Buffer,1,Readed);
// ...on va patienté quelque miliseconde.
WhatApen := WaitForSingleObject(Process.hProcess, 125);
Application.ProcessMessages;
until WhatApen = WAIT_OBJECT_0;
GetExitCodeProcess(Process.hProcess, WhatApen);
CloseHandle(PipeIn);
CloseHandle(Process.hProcess);
RunSpyStdOut:=WhatApen;
End; |
Partager