用delphi实现类似[MPLAB里ICD3烧写操控界面]的调用外部cmd命令方式

来源:互联网 发布:mac无鼠标右键 编辑:程序博客网 时间:2024/04/29 22:27

常规调用外部程序或者CMD窗口一般都是用Win32 API类似:

1.ShellExecute命令用于外部调用Windows关联应用程序打开某文件操作;

2.WinExec命令用于简单的CMD作业。


但为了实现介入CMD命令行窗口的敲指令一步一步的操作,就必须调用CreateProcess这个API来实现:


参考了别人写的一个代码段,作者未知。。。。


procedure CheckResult(b: Boolean); begin if not b then raise Exception.Create(SysErrorMessage(GetLastError)); end; function RunDOS(const CommandLine: string): string; var HRead, HWrite: THandle; StartInfo: TStartupInfo; ProceInfo: TProcessInformation; b: Boolean; sa: TSecurityAttributes; inS: THandleStream; sRet: TStrings; begin Result := ''; FillChar(sa, sizeof(sa), 0); //设置允许继承,否则在NT和2000下无法取得输出结果 sa.nLength := sizeof(sa); sa.bInheritHandle := True; sa.lpSecurityDescriptor := nil; b := CreatePipe(HRead, HWrite, @sa, 0); CheckResult(b); FillChar(StartInfo, SizeOf(StartInfo), 0); StartInfo.cb := SizeOf(StartInfo); StartInfo.wShowWindow := SW_HIDE; //使用指定的句柄作为标准输入输出的文件句柄,使用指定的显示方式 StartInfo.dwFlags := STARTF_USESTDHANDLES or STARTF_USESHOWWINDOW; StartInfo.hStdError := HWrite; StartInfo.hStdInput := GetStdHandle(STD_INPUT_HANDLE); //HRead; StartInfo.hStdOutput := HWrite; //  ShellExecute和WinExec命令用于简单的CMD作业。如果要完全控制一个新进程,就必须调用CreateProcess。b := CreateProcess(nil, //lpApplicationName: PChar PChar(CommandLine), //lpCommandLine: PChar nil, //lpProcessAttributes: PSecurityAttributes nil, //lpThreadAttributes: PSecurityAttributes True, //bInheritHandles: BOOL CREATE_NEW_CONSOLE, nil, nil, StartInfo,  //指向一个STARTUPINFO结构,该结构定义了新进程的主窗口将如何显示。ProceInfo);   //指向PROCESS_INFORMATION结构,该结构接受关于新进程的表示信息。//而真正感兴趣的返回值发生于作为参数传送的结构中 (PROCESS_INFORMATION)。CreateProcess返回该结构中的进程ID及其句柄,以及初始线程ID及其句柄。CheckResult(b); WaitForSingleObject(ProceInfo.hProcess, INFINITE); inS := THandleStream.Create(HRead); if inS.Size > 0 then begin sRet := TStringList.Create; sRet.LoadFromStream(inS); Result := sRet.Text; sRet.Free; end; inS.Free; CloseHandle(HRead); CloseHandle(HWrite); end;

这个代码能正常运行,但是对于ICD3的cmd操控程序会先憋很久突然爆出一堆字符串结果,不忍直视。所以我需要修改其线程等待和返回的方式:


未完待续。。。。。。。。。。

。。。

。。


0 0
原创粉丝点击