Delphi调用命令行命令并获取返回信息


本文整理自网络,侵删。

 procedure CmdExecAndView(FileName: string; memo: TMemo);
procedure _AddInfo(mmInfo:TMemo; S: string; var line: string); 
var 
    i, p: Integer;
begin 
    if mmInfo.Lines.Count > 800 then 
      mmInfo.Lines.Clear;
    for i := 0 to Length(S) - 1 do 
      if S[i] = #13 then S[i] := ' '; 
    line := line + S;
    p := Pos(#10, line); 
    if p > 0 then 
    begin 
      mmInfo.Lines.Add(Copy(line, 1, p - 1)); 
      line := Copy(line, p + 1, Length(line) - p); 
    end; 
end; 
var 
  hReadPipe, hWritePipe: THandle; 
  si: STARTUPINFO; 
  lsa: SECURITY_ATTRIBUTES; 
  pi: PROCESS_INFORMATION; 
  cchReadBuffer: DWORD; 
  ph: PChar; 
  fname: PChar; 
  line: string; 
begin 
    fname := allocmem(1024); 
    ph := AllocMem(1024); 
    lsa.nLength := sizeof(SECURITY_ATTRIBUTES); 
    lsa.lpSecurityDescriptor := nil; 
    lsa.bInheritHandle := True; 
    if CreatePipe(hReadPipe, hWritePipe, @lsa, 0) = false then 
        Exit;
    fillchar(si, sizeof(STARTUPINFO), 0); 
    si.cb := sizeof(STARTUPINFO); 
    si.dwFlags := (STARTF_USESTDHANDLES or STARTF_USESHOWWINDOW); 
    si.wShowWindow := SW_HIDE; 
    si.hStdOutput := hWritePipe; 
    si.hStdError := hWritePipe; 
    StrPCopy(fname, FileName); 
    if CreateProcess(nil, fname, nil, nil, true, 0, nil, nil, si, pi) = False then 
    begin 
        FreeMem(ph); 
        FreeMem(fname); 
        Exit; 
    end; 
    CloseHandle(hWritePipe); 
    while (true) do 
    begin 
        if not PeekNamedPipe(hReadPipe, ph, 1, @cchReadBuffer, nil, nil) then break; 
        if cchReadBuffer <> 0 then 
        begin 
            if ReadFile(hReadPipe, ph^, 512, cchReadBuffer, nil) = false then break; 
            ph[cchReadbuffer] := chr(0); 
            _AddInfo(memo, ph, line); 
        end 
        else if (WaitForSingleObject(pi.hProcess, 0) = WAIT_OBJECT_0) then break; 
        Application.ProcessMessages; 
        Sleep(200); 
    end; 
    ph[cchReadBuffer] := chr(0); 
    _AddInfo(memo, ph, line); 
    CloseHandle(hReadPipe); 
    CloseHandle(pi.hThread); 
    CloseHandle(pi.hProcess); 
    FreeMem(ph); 
    FreeMem(fname); 
end;
用的时候就  CmdExecAndView('ping 202.100.197.50 -t',Memo1);

相关阅读 >>

Delphi android 关闭应用程序对话框询问

Delphi 封装的tidhttp get post 请求

Delphi计算md5

Delphi generics collections tdictionary 用法

Delphi判断文件夹(目录)是否存在,不存在就创建一个

Delphi 从资源文件中加载字符

Delphi android 平台加载文件

Delphi 权限控制(Delphi tactionlist方案)

Delphi twebbrowser:确定带有框架的页面何时完成

Delphi 让"显示桌面"功能对你的窗口无效

更多相关阅读请进入《Delphi》频道 >>



打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...