執行控制台程式並且獲得它的輸出結果

2021-04-17 06:52:42 字數 1908 閱讀 4942

前幾日遇到的問題在各位的幫助下已經圓滿解決,現在吧這段**寫出來,可能會有一點用處。

procedure checkresult(b: boolean);

begin

if not b then

raise exception.create(syserrormessage(getlasterror));

end;

function rundos(const prog, commandline,dir: string;var exitcode:dword): string;

varhread,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+startf_useshowwindow;

startinfo.hstderror  := hwrite;

startinfo.hstdinput  := getstdhandle(std_input_handle);//hread;

startinfo.hstdoutput  := hwrite;

pchar(commandline),    //lpcommandline: pchar

nil,    //lpprocessattributes: psecurityattributes

nil,    //lpthreadattributes: psecurityattributes

true,    //binherithandles: bool

create_new_console,

nil,       

pchar(dir),

startinfo,

proceinfo    );

checkresult(b);

waitforsingleobject(proceinfo.hprocess,infinite);

getexitcodeprocess(proceinfo.hprocess,exitcode);

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;

Createprocess控制台程式輸出重定向

spawnlp p wait,netstat e s n r a p ip null shellexecute null,null,ping.exe 168.192.0.1 1.txt null,sw shownormal system format a q null execlp expand.e...

MFC程式顯示控制台輸出

有的時候,我們用c寫的一些東西,可能需要mfc作為ui輸入引數進行測試,但是程式裡有大量的printf操作,這就需要mfc程式啟動的時候同時開啟 乙個控制台,用於標準輸出 查詢網路,大致方法有以下兩種 1,新增乙個全域性函式,內容如下,再程式啟動的時候呼叫 void initconsolewindo...

MFC程式顯示控制台輸出

有的時候,我們用c寫的一些東西,可能需要mfc作為ui輸入引數進行測試,但是程式裡有大量的printf操作,這就需要mfc程式啟動的時候同時開啟 乙個控制台,用於標準輸出 查詢網路,大致方法有以下兩種 1,新增乙個全域性函式,內容如下,再程式啟動的時候呼叫 void initconsolewindo...