在代码里面需要启动一个命令行小程序来协助完成一个功能,而且这个小程序运行的时候不能闪出窗口,所以用system()加重定向的方法就不用考虑了。
那么估计只能是用CreatProcess或者Winexec这两个方法了,因为可以隐藏小程序执行时的窗口。可是我有需要获得小程序的输出结果。怎么办?有的朋友告诉我用获取exitcode或者改变输出句柄STARTUPINFO.hStdOutput的方法,这两种方法要怎么实现,关键我是要得到原本在命令行窗口上输出的那些printf字符串。命令行小程序没有源码。

解决方案 »

  1.   

    管道重定向。下面这段代码是把windows的ping 程序的内容输出到edit里面的。HANDLE hReadPipe;
    HANDLE hWritePipe;
    SECURITY_ATTRIBUTES sat;
    STARTUPINFO startupinfo;
    PROCESS_INFORMATION pinfo;
    BYTE buffer[1024];
    DWORD byteRead;
    CString rString;UpdateData();
    if(m_Host=="")
    {
    MessageBox("主机地址不能为空!");
    return;
    }
    m_Host="c:\\windows\\ping.exe "+m_Host;sat.nLength=sizeof(SECURITY_ATTRIBUTES);
    sat.bInheritHandle=true;
    sat.lpSecurityDescriptor=NULL;
    if(!CreatePipe(&hReadPipe,&hWritePipe,&sat,NULL))
    {
    MessageBox("Create Pipe Error!");
    return;
    }
    startupinfo.cb=sizeof(STARTUPINFO);
    GetStartupInfo(&startupinfo);
    startupinfo.hStdError=hWritePipe;
    startupinfo.hStdOutput=hWritePipe;
    startupinfo.dwFlags=STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
    startupinfo.wShowWindow=SW_HIDE;
    if(!CreateProcess(NULL,m_Host.GetBuffer(m_Host.GetLength()+1),NULL, NULL, TRUE, NULL, NULL, NULL,&startupinfo,&pinfo))
    {
    MessageBox("create process error!");
    return;
    }
    CloseHandle(hWritePipe);
    while(true)
    {
    RtlZeroMemory(buffer,1024);
    if(ReadFile(hReadPipe,buffer,1023,&byteRead,NULL)==NULL)
    break;
    //IDC_EDIT1是那个edit
    ::SendMessage(GetDlgItem(IDC_EDIT1)->m_hWnd,EM_SETSEL,-1,0);
    ::SendMessage(GetDlgItem(IDC_EDIT1)->m_hWnd,EM_REPLACESEL,false,(long)buffer);
    }
    CloseHandle(hReadPipe);
    m_Host.ReleaseBuffer();
      

  2.   

    支持楼上,我记得<UNIX网络编程>好象提过这种方法