博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Delphi 获取命令行输出的函数
阅读量:4975 次
发布时间:2019-06-12

本文共 1909 字,大约阅读时间需要 6 分钟。

function GetDosOutput(CommandLine: string; Work: string = 'C:\'): string;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  Result := '';  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 := Work;    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;            Result := Result + 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;

上面的代码执行时会阻塞GUI线程,你可以将上面的代码封装到一个TThread的字类中执行, 也就是在线程中执行,使用MsgWaitForMultipleObjects替换WaitForSingleObject,当Windows消息到达时调用Application.ProcessMessages,就像下面这样:

repeat   case MsgWaitForMultipleObjects(1, PI.hProcess,False, INFINITE, QS_ALLINPUT )of  WAIT_OBJECT_0:     Break;  WAIT_OBJECT_0+1:     Application.ProcessMessages();   else     Break;// should never happen   end; until False;

转载于:https://www.cnblogs.com/MaxWoods/p/3742104.html

你可能感兴趣的文章
【noip2004】虫食算——剪枝DFS
查看>>
python 多进程和多线程的区别
查看>>
sigar
查看>>
iOS7自定义statusbar和navigationbar的若干问题
查看>>
[Locked] Wiggle Sort
查看>>
deque
查看>>
c#中从string数组转换到int数组
查看>>
java小技巧
查看>>
POJ 3204 Ikki's Story I - Road Reconstruction
查看>>
toad for oracle中文显示乱码
查看>>
SQL中Group By的使用
查看>>
两个表格中数据不用是一一对应关系--来筛选不同数据,或者相同数据
查看>>
静态方法是否属于线程安全
查看>>
js05-DOM对象二
查看>>
mariadb BINLOG_FORMAT = STATEMENT 异常
查看>>
C#生成随机数
查看>>
Java回顾之多线程
查看>>
机电行业如何进行信息化建设
查看>>
9、总线
查看>>
2018 Multi-University Training Contest 10 - Count
查看>>