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 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
| function Win32ExecuteAndCapture(const ProgName: String ;
const Parameters: String; const Folder: String ; var Output: TStrings;
const OnNewLine: TNotifyEvent): Cardinal;
Const
LF = #10 ;
CR = #13 ;
Var
StartupInfo : TStartupInfo ;
ProcessInfo : TProcessInformation ;
SecurityAttributes : TSecurityAttributes ;
TempHandle,
WriteHandle,
ReadHandle : THandle ;
ReadBuf : Array[0..256] Of Char;
BytesRead : Cardinal;
LineBuf : Array[0..256] Of Char;
LineBufPtr : Integer;
Newline : Boolean;
I : Integer;
Procedure OutputLine;
Begin
LineBuf[LineBufPtr]:=#0;
With Output Do
If Newline Then Add(LineBuf)
Else Strings[Count-1]:=LineBuf;
Newline:=False;
LineBufPtr:=0;
If Assigned(OnNewLine) Then
OnNewLine(Output);
End;
begin
FillChar(StartupInfo,SizeOf(StartupInfo), 0);
FillChar(ReadBuf, SizeOf(ReadBuf), 0);
FillChar(SecurityAttributes, SizeOf(SecurityAttributes), 0);
LineBufPtr:=0;
Newline:=True;
If Not Assigned(Output) Then
Output:=THashedStringList.Create;
With SecurityAttributes Do
Begin
nLength:=SizeOf(SecurityAttributes);
bInheritHandle:=True;
End;
If Not CreatePipe(ReadHandle, WriteHandle, @SecurityAttributes, 0) Then
RaiseLastOSError;
Try
If Win32Platform=VER_PLATFORM_WIN32_NT Then Begin
If Not SetHandleInformation(ReadHandle, HANDLE_FLAG_INHERIT, 0) Then
RaiseLastOSError ;
End
Else Begin
If Not DuplicateHandle(GetCurrentProcess, ReadHandle, GetCurrentProcess, @TempHandle, 0, True, DUPLICATE_SAME_ACCESS) Then
RaiseLastOSError;
CloseHandle(ReadHandle);
ReadHandle:=TempHandle;
End;
With StartupInfo Do
Begin
cb:=SizeOf(StartupInfo);
dwFlags:=STARTF_USESTDHANDLES or STARTF_USESHOWWINDOW;
wShowWindow:=SW_HIDE;
hStdOutput:=WriteHandle;
End;
If Not CreateProcess( Nil, PChar(ProgName+' '+Parameters), Nil, Nil, True, NORMAL_PRIORITY_CLASS Or CREATE_NO_WINDOW, Nil, PChar(Folder), StartupInfo, ProcessInfo) Then
RaiseLastOSError;
CloseHandle(ProcessInfo.hThread);
CloseHandle(WriteHandle);
Try
While ReadFile(ReadHandle, ReadBuf, SizeOf(ReadBuf), BytesRead, Nil) Do
For I:=0 to BytesRead-1 Do
If (ReadBuf[I]=LF) Then Newline:= True
Else If (ReadBuf[I]=CR) Then OutputLine
Else Begin
LineBuf[LineBufPtr]:=ReadBuf[I];
Inc(LineBufPtr);
If LineBufPtr>=(SizeOf(LineBuf)-1) Then
Begin
Newline:=True;
OutputLine;
End ;
End ;
WaitForSingleObject(ProcessInfo.hProcess, TerminationWaitTime);
If Not GetExitCodeProcess(ProcessInfo.hProcess, Result) Then
RaiseLastOSError ;
OutputLine;
Finally
CloseHandle(ProcessInfo.hProcess)
End;
Finally
CloseHandle(ReadHandle);
End;
end; |
Partager