废话不多说,大家来看代码
bool __fastcall TForm1::RunCmd(AnsiString cmd,TStringList *stringlist)
{
TMemoryStream *memstream=new TMemoryStream();
AnsiString rn="\\r\\n";
PROCESS_INFORMATION proc;
STARTUPINFO start;
SECURITY_ATTRIBUTES sa;
long ret;
unsigned long lngBytesread;
HANDLE hReadPipe,hWritePipe;
char *strBuff=(char *)malloc(256);
if(strBuff==NULL)
{
return false;
}
sa.nLength = sizeof(SECURITY_ATTRIBUTES);
sa.bInheritHandle=true;
sa.lpSecurityDescriptor=NULL;
ret=CreatePipe(&hReadPipe,&hWritePipe,&sa,0);
if(ret==0)
{
//创建管道失败
return false;
}
memset(&start,0x00,sizeof(STARTUPINFO));
start.cb=sizeof(STARTUPINFO);
start.dwFlags=STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
start.hStdOutput=hWritePipe;
start.hStdError=hWritePipe;
bool retc=CreateProcess(NULL,cmd.c_str(),NULL,NULL,true, 0, 0, NULL, &start, &proc);
if(!retc)
{
return false;
}
CloseHandle(hWritePipe);
unsigned long len;
memstream->Position=0;
while(true)
{
memset(strBuff,0x00,256);
GetFileSize(hReadPipe,&len);
ret = ReadFile(hReadPipe, strBuff, 256, &lngBytesread,NULL);
if(ret==0)
{
break;
}
else
{
memstream->Write(strBuff,lngBytesread);
}
}
CloseHandle(proc.hProcess);
CloseHandle(proc.hThread);
CloseHandle(hReadPipe);
memstream->Position=0;
free(strBuff);
stringlist->LoadFromStream(memstream);
memstream->Clear();
delete memstream;
return true;
}
以上为一个使用管道获取命令行模式的程序的运行结果的函数。
使用代码
TStringList *StrList=new TStringList;
AnsiString strcmd;
RunCmd(strcmd,StrList);
结果保留再StrList中。