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 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
| unit DosCommandUnit;
{
Classe qui execute des commandes DOS dans un thread, visible dans un TMemo
Ex :
dosCommand := TDosCommand.Create(memo);
dosCommand.add('cd C:\Apps');
dosCommand.add('dir');
}
interface
uses Vcl.StdCtrls, Windows, System.Classes, Forms, Vcl.ComCtrls;
type
TThreadDosCommand = class(TThread)
private
commandLine: string;
memo: TMemo;
function add(CommandLine: string): string;
protected
procedure Execute; override;
end;
TDosCommand = class
private
threadDC: TThreadDosCommand;
public
Constructor Create(memo: TMemo);
procedure add(commandLine: string);
end;
implementation
{ TThreadDosCommand }
function TThreadDosCommand.add(commandLine: string): string;
begin
Self.commandLine := commandLine;
end;
procedure TThreadDosCommand.Execute;
var
SA: TSecurityAttributes;
SI: TStartupInfo;
PI: TProcessInformation;
StdOutPipeRead, StdOutPipeWrite: THandle;
WasOK: Boolean;
Buffer: array[0..255] of AnsiChar;
BytesRead: Cardinal;
WorkDir: string;
Handle: Boolean;
begin
inherited;
with SA do begin
nLength := SizeOf(SA);
bInheritHandle := True;
lpSecurityDescriptor := nil;
end;
CreatePipe(StdOutPipeRead, StdOutPipeWrite, @SA, 0);
try
with SI do
begin
FillChar(SI, SizeOf(SI), 0);
cb := SizeOf(SI);
dwFlags := STARTF_USESHOWWINDOW or STARTF_USESTDHANDLES;
wShowWindow := SW_HIDE;
hStdInput := GetStdHandle(STD_INPUT_HANDLE); // don't redirect stdin
hStdOutput := StdOutPipeWrite;
hStdError := StdOutPipeWrite;
end;
WorkDir := 'C:\';
Handle := CreateProcess(nil, PChar('cmd.exe /C ' + CommandLine),
nil, nil, True, 0, nil,
PChar(WorkDir), SI, PI);
CloseHandle(StdOutPipeWrite);
if Handle then
try
repeat
WasOK := ReadFile(StdOutPipeRead, Buffer, 255, BytesRead, nil);
if BytesRead > 0 then
begin
Buffer[BytesRead] := #0;
memo.Text := memo.Text + Buffer;
end;
until not WasOK or (BytesRead = 0);
WaitForSingleObject(PI.hProcess, INFINITE);
finally
CloseHandle(PI.hThread);
CloseHandle(PI.hProcess);
end;
finally
CloseHandle(StdOutPipeRead);
end;
end;
{ TDosCommand }
constructor TDosCommand.Create(memo: TMemo);
begin
threadDC := TThreadDosCommand.Create(False);
threadDC.memo := memo;
end;
procedure TDosCommand.add(CommandLine: string);
begin
threadDC.add(CommandLine);
end;
end. |
Partager