MFC:在win32文本区域(mfc应用程序)中执行进程时异步(并发)显示进程的输出

时间:2012-02-28 10:13:02

标签: c++ mfc winpe

我想在MFC中开发一个应用程序,它可以启动一个冗长的控制台进程并在32位Windows应用程序的文本区域上同时提供它的输出。

我使用了管道,但只在进程终止后才显示输出。 我试过_popen,它适用于基于控制台的应用程序,但与win32应用程序不兼容。

在搜索互联网时,我发现了很多使用CLR的代码,但我需要在MFC中使用某种方式,而不使用.Net .. Plz帮助。

提前感谢: - )

这是启动应用程序的代码:

void CAppMgr_BackupsDlg::ExecuteExternalFile(CString csExeName, CString csArguments)
{

CString csExecute;
csExecute=csExeName + " " + csArguments;

SECURITY_ATTRIBUTES secattr; 
ZeroMemory(&secattr,sizeof(secattr));
secattr.nLength = sizeof(secattr);
secattr.bInheritHandle = TRUE;

HANDLE rPipe, wPipe;

//Create pipes to write and read data
CreatePipe(&rPipe,&wPipe,&secattr,0);

STARTUPINFO sInfo; 
ZeroMemory(&sInfo,sizeof(sInfo));
PROCESS_INFORMATION pInfo; 
ZeroMemory(&pInfo,sizeof(pInfo));
sInfo.cb=sizeof(sInfo);
sInfo.dwFlags=STARTF_USESTDHANDLES;
sInfo.hStdInput=NULL; 
sInfo.hStdOutput=wPipe; 
sInfo.hStdError=wPipe;
char command[1024]; 
strcpy(command, csExecute.GetBuffer(csExecute.GetLength()));

//Create the process here.
CreateProcess(0, command,0,0,TRUE,
      NORMAL_PRIORITY_CLASS|CREATE_NO_WINDOW,0,0,&sInfo,&pInfo);
CloseHandle(wPipe);

//now read the output pipe here.
char buf[100];
DWORD reDword; 
CString m_csOutput,csTemp;
BOOL res;
do
{
    res=::ReadFile(rPipe,buf,100,&reDword,0);
    csTemp=buf;
    m_csOutput=csTemp.Left(reDword);
            DisplayToTextArea(m_csOutput);
}
while(res);
}

PS:我在x86 windows 7上使用Visual Studio 2010.我正在使这个代码与winPE集成,因此非常需要MFC。

1 个答案:

答案 0 :(得分:0)

问题似乎是读取管道的循环阻塞了应用程序的UI主线程,因此在循环结束之前不会更新对话框。

您可以采取一些措施来解决此问题,但最简单的方法是在调用DisplayToTextArea之后向您的do-while循环添加一个消息处理循环:

 MSG msg;
 while (GetMessage(&msg, NULL, 0, 0)) 
 {
    TranslateMessage(&msg);
    DispatchMessage(&msg);  // send to window proc
 }