• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

[转]Delphi调用cmd并取得输出文本

原作者: [db:作者] 来自: [db:来源] 收藏 邀请
//转自http://www.oschina.net/code/snippet_136241_3980 

1
procedure CheckResult(b: Boolean); 2 begin 3 if not b then 4 raise Exception.Create(SysErrorMessage(GetLastError)); 5 end; 6 7 function RunDOS(const CommandLine: string): string; 8 var 9 HRead, HWrite: THandle; 10 StartInfo: TStartupInfo; 11 ProceInfo: TProcessInformation; 12 b: Boolean; 13 sa: TSecurityAttributes; 14 inS: THandleStream; 15 sRet: TStrings; 16 begin 17 Result := ''; 18 FillChar(sa, sizeof(sa), 0); 19 //设置允许继承,否则在NT和2000下无法取得输出结果 20 sa.nLength := sizeof(sa); 21 sa.bInheritHandle := True; 22 sa.lpSecurityDescriptor := nil; 23 b := CreatePipe(HRead, HWrite, @sa, 0); 24 CheckResult(b); 25 26 FillChar(StartInfo, SizeOf(StartInfo), 0); 27 StartInfo.cb := SizeOf(StartInfo); 28 StartInfo.wShowWindow := SW_HIDE; 29 //使用指定的句柄作为标准输入输出的文件句柄,使用指定的显示方式 30 StartInfo.dwFlags := STARTF_USESTDHANDLES or STARTF_USESHOWWINDOW; 31 StartInfo.hStdError := HWrite; 32 StartInfo.hStdInput := GetStdHandle(STD_INPUT_HANDLE); //HRead; 33 StartInfo.hStdOutput := HWrite; 34 35 b := CreateProcess(nil, //lpApplicationName: PChar 36 PChar(CommandLine), //lpCommandLine: PChar 37 nil, //lpProcessAttributes: PSecurityAttributes 38 nil, //lpThreadAttributes: PSecurityAttributes 39 True, //bInheritHandles: BOOL 40 CREATE_NEW_CONSOLE, 41 nil, 42 nil, 43 StartInfo, 44 ProceInfo); 45 46 CheckResult(b); 47 WaitForSingleObject(ProceInfo.hProcess, INFINITE); 48 49 inS := THandleStream.Create(HRead); 50 if inS.Size > 0 then 51 begin 52 sRet := TStringList.Create; 53 sRet.LoadFromStream(inS); 54 Result := sRet.Text; 55 sRet.Free; 56 end; 57 inS.Free; 58 59 CloseHandle(HRead); 60 CloseHandle(HWrite); 61 end;

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
DelphiXE2使用自带vclstyle换肤发布时间:2022-07-18
下一篇:
Delphi操作Excel(2)---Stringgrid导出到Excel发布时间:2022-07-18
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap