
代码如下:
function CallCmd(CommandStr: string): string; const ReadBuffer = 4096; var Security: TSecurityAttributes; si: TStartUpInfo; pi: PROCESS_INFORMATION; hRead, hWrite: THandle; len: DWORD; ExitCode: DWORD; Buffer: PAnsiChar; hProcess: Integer; begin with Security do begin nlength := SizeOf(TSecurityAttributes); binherithandle := true; lpsecuritydescriptor := nil; end; if not Createpipe(hRead, hWrite, @Security, 0) then begin ShowMessage('Pipe Create Error 0x01'); end; //GetStartupInfo(si); FillChar(si,Sizeof(si), #0); with si do begin cb := SizeOf(si); dwFlags := STARTF_USESTDHANDLES or STARTF_USESHOWWINDOW; wShowWindow := SW_HIDE; hStdOutput := hWrite; hStdError := hWrite; end; if not CreateProcess(nil, PWideChar('cmd.exe /c ' + CommandStr), 0, 0, TRUE, 0, 0, 0, si, pi) then begin ShowMessage('Create Process Error'); end; CloseHandle(hWrite); Buffer := AllocMem(ReadBuffer + 1); while True do begin PeekNamedPipe(hRead, 0, 0, 0, @len, 0); if len <> 0 then begin ReadFile(hRead, Buffer[0], ReadBuffer, dword(len), nil); {out date} with Form1.mmo1 do begin Lines.Text := Lines.Text + Buffer; SelStart := Length(Lines.Text); SelLength := 0; end; end else begin //Break; GetExitCodeProcess(pi.hProcess, ExitCode); if ExitCode <> STILL_ACTIVE then begin CloseHandle(hRead); Break; end; end; end; end;
本文介绍了一个用于在Delphi中通过调用CMD执行指定命令并获取其输出的函数。该函数创建了一个管道来捕获CMD命令的输出,并通过设置启动信息实现了对标准输出的重定向。
1716

被折叠的 条评论
为什么被折叠?



