delphi获取DOS命令行输出函数 运行CMD命令并获取结果
procedure TForm1.Button4Click(Sender: TObject); var hReadPipe,hWritePipe:THandle; si:STARTUPINFO; lsa:SECURITY_ATTRIBUTES; pi:PROCESS_INFORMATION; mDosScreen:String; cchReadBuffer:DWORD; ph:PansiChar; fname:PChar; i,j:integer; str,TEMP,ip:string; K:Integer; begin Memo1.Clear; fname:=allocmem(255); ph:=AllocMem(5000); lsa.nLength :=sizeof(SECURITY_ATTRIBUTES); lsa.lpSecurityDescriptor :=nil; lsa.bInheritHandle :=True; try try if CreatePipe(hReadPipe,hWritePipe,@lsa,0)=false then begin ShowMessage('Can not create pipe!'); exit; end; fillchar(si,sizeof(STARTUPINFO),0); si.cb :=sizeof(STARTUPINFO); si.dwFlags :=(STARTF_USESTDHANDLES or STARTF_USESHOWWINDOW); si.wShowWindow :=SW_HIDE; si.hStdOutput :=hWritePipe; StrPCopy(fname,'ping baidu.com');//执行命令 if CreateProcess( nil, fname, nil, nil, true, 0, nil, nil, si, pi) = False then begin ShowMessage('can not create process'); FreeMem(ph); FreeMem(fname); Exit; end; while(true) do begin if not PeekNamedPipe(hReadPipe,ph,1,@cchReadBuffer,nil,nil) then break; if cchReadBuffer<>0 then begin if ReadFile(hReadPipe,ph^,4096,cchReadBuffer,nil)=false then break; ph[cchReadbuffer]:=chr(0); if ph<>'' then Memo1.Lines.Add(ph); end else if(WaitForSingleObject(pi.hProcess ,0)=WAIT_OBJECT_0) then break; Application.ProcessMessages; Sleep(100); end; ph[cchReadBuffer]:=chr(0); if ph<>'' then Memo1.Lines.Add(StringReplace(ph,#13#10,'',[rfReplaceAll])); CloseHandle(hReadPipe); CloseHandle(pi.hThread); CloseHandle(pi.hProcess); CloseHandle(hWritePipe); FreeMem(ph); FreeMem(fname); except end; finally end; end;
posted on 2020-03-16 17:23 windsonvip 阅读(1771) 评论(0) 编辑 收藏 举报