DelphiX执⾏shell命令,并获取返回结果Delphi X执⾏shell命令,并获取返回结果
话不多说,我们上代码; 建议你把以下代码抄到线程⾥⾯运⾏。
uses
System.Classes, Winapi.Windows, System.SysUtils;
function RunDosCommand2(Command: string): string;
const
//预防返回量⼤,我们设置4096个字节
DEF_OUTPUT_BUFSIZE = 4096;
var
hReadPipe: THandle;
hWritePipe: THandle;
SI: TStartUpInfo;
PI: TProcessInformation;
SA: TSecurityAttributes;
BytesRead: DWORD;
Dest : array[0..DEF_OUTPUT_BUFSIZE - 1] of byte;
CmdLine : array[0..512] of byte;
Avail, ExitCode, wrResult: DWORD;
osVer: TOSVERSIONINFO;
//tmpstr: AnsiString;
tmpstr2 :AnsiString;
sResult :AnsiString;
begin
osVer.dwOSVersionInfoSize := Sizeof(TOSVERSIONINFO);
GetVersionEX(osVer);
if osVer.dwPlatformId = VER_PLATFORM_WIN32_NT then
begin
SA.nLength := SizeOf(SA);
createprocessaSA.lpSecurityDescriptor := nil; //@SD;
SA.bInheritHandle := True;
CreatePipe(hReadPipe, hWritePipe, @SA, 0);
end
else
CreatePipe(hReadPipe, hWritePipe, nil, DEF_OUTPUT_BUFSIZE);
try
FillChar(SI, SizeOf(SI), 0);
SI.cb := SizeOf(TStartUpInfo);
SI.wShowWindow := SW_HIDE;
SI.dwFlags := STARTF_USESHOWWINDOW;
SI.dwFlags := SI.dwFlags or STARTF_USESTDHANDLES;
SI.hStdOutput := hWritePipe;
SI.hStdError := hWritePipe;
//save2Log(Command);
if CreateProcess(nil, DoStrToWideChar(Command), nil, nil, True, NORMAL_PRIORITY_CLASS, nil,nil, SI, PI) then begin
ExitCode := 0;
while ExitCode = 0 do
begin
wrResult := WaitForSingleObject(PI.hProcess, 500);
if PeekNamedPipe(hReadPipe, @Dest[0], DEF_OUTPUT_BUFSIZE, @Avail, nil, nil) then
begin
if Avail > 0 then
begin
try
try
FillChar(Dest, SizeOf(Dest), 0);
ReadFile(hReadPipe, Dest, Avail, BytesRead, nil);
SetLength(tmpstr2, BytesRead);
CopyMemory(PChar(tmpstr2), @Dest[0], BytesRead);
sResult := sResult + tmpstr2;
//如果返回不是⼀次性(譬如说:ping命令,则可以在这⾥发⼀个windows消息到主窗体,实时显⽰当前收到的返回) finally
end;
end;
end;
if wrResult <> WAIT_TIMEOUT then ExitCode := 1;
end;
GetExitCodeProcess(PI.hProcess, ExitCode);
CloseHandle(PI.hProcess);
CloseHandle(PI.hThread);
end;
finally
CloseHandle(hReadPipe);
CloseHandle(hWritePipe);
end;
Result := sResult;
end;
function ThdConversion.DoStrToWideChar(s: string): PWideChar;
const
DEF_INPUT_BUFFSIZE = 4096;
var
Buff: array[0..DEF_INPUT_BUFFSIZE - 1] of WideChar;
WChar: PWideChar;
begin
FillChar(Buff, Length(Buff), $00);
WChar := StringToWideChar(s, Buff, Length(s) + 1);
Result := WChar;
end;
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论