|
发表于 2020-3-30 17:45:01
|
显示全部楼层
重定向,给你个例子:
char cmdbuffer[1024];
HANDLE hReadPipe;
HANDLE hReadPipe2;
HANDLE hWritePipe;
HANDLE hWritePipe2;
DWORD __stdcall ThreadFun(void *pVoid)
{
HWND hwnd = *((HWND *)pVoid);
SECURITY_ATTRIBUTES sat;
STARTUPINFO startupinfo;
PROCESS_INFORMATION pinfo;
BYTE buffer[1024];
DWORD byteRead;
CString rString;
sat.nLength=sizeof(SECURITY_ATTRIBUTES);
sat.bInheritHandle=true;
sat.lpSecurityDescriptor=NULL;
if(!CreatePipe(&hReadPipe,&hWritePipe,&sat,NULL))
{
MessageBox(NULL,"Create Pipe Error!","error!",MB_OK);
return 0;
}
if(!CreatePipe(&hReadPipe2,&hWritePipe2,&sat,NULL))
{
MessageBox(NULL,"Create Pipe2 Error!","error!",MB_OK);
return 0;
}
startupinfo.cb=sizeof(STARTUPINFO);
GetStartupInfo(&startupinfo);
startupinfo.hStdError=hWritePipe;
startupinfo.hStdOutput=hWritePipe;
startupinfo.hStdInput=hReadPipe2;
startupinfo.dwFlags=STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
startupinfo.wShowWindow=SW_HIDE;
if(!CreateProcess(NULL,"c:\\winnt\\system32\\cmd.exe",NULL, NULL, TRUE, NULL, NULL, NULL,&startupinfo,&pinfo))
{
MessageBox(NULL,"create process error!","Error!",MB_OK);
return 0;
}
CloseHandle(hWritePipe);
CloseHandle(hReadPipe2);
CloseHandle(pinfo.hThread);
CloseHandle(pinfo.hProcess);
while(true)
{
RtlZeroMemory(buffer,1024);
if(ReadFile(hReadPipe,buffer,1023,&byteRead,NULL)==NULL)
break;
//buffer里就是屏幕上显示的内容
}
CloseHandle(hReadPipe);
CloseHandle(hWritePipe2);
return 0;
}
//创建线程:
HANDLE hThread = NULL;
hThread = CreateThread(NULL,0,ThreadFun,&m_hWnd,0,&dwThreadId);//m_hWnd这个参数你根据你的需要决定要不要
if (hThread == NULL)
{
MessageBox("CreateThread failed.", "main", MB_OK );
}
else
{
CloseHandle( hThread );
}
//往consel程序里写命令:
strcpy(cmdbuffer,"dir");
strcat(cmdbuffer,"\r\n");//一定要有回车换行
WriteFile(hWritePipe2,cmdbuffer,strlen(cmdbuffer),&byteRead,NULL); |
|