代码大致如下:
      bool success = CreateProcess(....);
      if(success)
      {
          //这里如果调用Thread.Sleep(100)或者WaitForSingleObject(pi.hProcess,100)
          // 那么下面的语句就能找到该住窗体的句柄。
          Handle hwnd = FindWindow(className,windowName)
      }那么问题是我并不知道我到底应该阻塞当前进程多少时间,新创建的进程才能把主窗体显示出来,我才能在当前进程通过FindWidow去找到相应窗体的句柄,而我也不想当前进程一直阻塞。问各位大虾可有解决方法!!!!

解决方案 »

  1.   

    需要线程同步
    可以用事件对象
    大致原理就是设置一全局的事件对象,初始值为没有信号,当你的CreateProcess中创建完成以后,将此对象设置成有信号,而当前线程中则不需要使用Thread.Sleep(),它等待同步事件变成有信号时就可以执行FindWindow()的操作了
      

  2.   

    做个循环查找
    for(int i=0; i<MAX; i++)
    {
       Handle hwnd = FindWindow(className,windowName)
       if(NULL != hwnd)
       break;
       sleep(10);
    }
      

  3.   

    用WaitForInputIdle函数DWORD WaitForInputIdle(HANDLE hProcess,DWORD dwMilliseconds);The WaitForInputIdle function enables a thread to suspend its execution until the specified process has finished its initialization and is waiting for user input with no input pending. This can be useful for synchronizing a parent process and a newly created child process. When a parent process creates a child process, the CreateProcess function returns without waiting for the child process to finish its initialization. Before trying to communicate with the child process, the parent process can use WaitForInputIdle to determine when the child's initialization has been completed. For example, the parent process should use WaitForInputIdle before trying to find a window associated with the child process.
      

  4.   

    楼上的两种方法我都用过。WaitForInputIdle是正解,用循环等待应该也没什么问题。
      

  5.   

    對用:
    if (WaitForInputIdle(hProcess,INFINITE) == 0)
    {
       HWND hWnd = FindWindow(szClassName,szWindowTitle);
    }