EnumDesktopWindows(C ++)大约需要30分钟才能在Windows 10

时间:2016-03-15 18:05:28

标签: c++ windows winapi

仅在Windows 10上会出现此问题。在其他版本(如Windows 7)上运行正常。

在用户操作上,我有以下代码来查找另一个打开的应用程序窗口:

void zcTarget::LocateSecondAppWindow( void )
{
    ghwndAppWindow = NULL;
    CString csQuickenTitleSearch = "MySecondApp";
    ::EnumDesktopWindows( hDesktop, MyCallback, (LPARAM)(LPCTSTR)csTitleSearch );
}

使用回调函数:

BOOL CALLBACK MyCallback( HWND hwnd, LPARAM lParam)
{
   if ( ::GetWindowTextLength( hwnd ) == 0 )
   {
      return TRUE;
   }

   CString strText;
   GetWindowText( hwnd, strText.GetBuffer( 256 ), 256 );
   strText.ReleaseBuffer();

   if ( strText.Find( (LPCTSTR)lParam ) == 0 )
   {
      // We found the desired app HWND, so save it off, and return FALSE to
      // tell EnumDesktopWindows to stopping iterating desktop HWNDs.
      ghwndAppWindow = hwnd;

      return FALSE;
   }

   return TRUE;
} // This is the line after which call is not returned for about 30 mins

上面提到的这个回调函数被调用大约7次,每次都返回True。在此阶段,它会找到自己的应用程序窗口,通过该窗口调用EnumDesktopWindows。

它按预期返回True,但大约30分钟后没有任何反应。没有调试点。此时正在运行的应用程序没有响应。

如何解决此问题?

1 个答案:

答案 0 :(得分:1)

找到了另一条路。而不是通过Window名称,寻找过程帮助。使用进程名称获取进程,提取进程ID并获取窗口句柄。

void zcTarget::LocateSecondAppWindow( void )
 {
       PROCESSENTRY32 entry;
       entry.dwSize = sizeof(PROCESSENTRY32);
       HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);

       if (Process32First(snapshot, &entry) == TRUE)
       {
          while (Process32Next(snapshot, &entry) == TRUE)
          {
             if (_stricmp(entry.szExeFile, "myApp.exe") == 0)
             {  
                HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, entry.th32ProcessID);               

                EnumData ed = { GetProcessId( hProcess ) };
                if ( !EnumWindows( EnumProc, (LPARAM)&ed ) &&
                   ( GetLastError() == ERROR_SUCCESS ) ) {
                      ghwndQuickenWindow = ed.hWnd;
                }
                CloseHandle(hProcess);
                break;
             }
          }
       }
       CloseHandle(snapshot);
}

       BOOL CALLBACK EnumProc( HWND hWnd, LPARAM lParam ) {
       // Retrieve storage location for communication data
       zcmTaxLinkProTarget::EnumData& ed = *(zcmTaxLinkProTarget::EnumData*)lParam;
       DWORD dwProcessId = 0x0;
       // Query process ID for hWnd
       GetWindowThreadProcessId( hWnd, &dwProcessId );
       // Apply filter - if you want to implement additional restrictions,
       // this is the place to do so.
       if ( ed.dwProcessId == dwProcessId ) {
          // Found a window matching the process ID
          ed.hWnd = hWnd;
          // Report success
          SetLastError( ERROR_SUCCESS );
          // Stop enumeration
          return FALSE;
       }
       // Continue enumeration
       return TRUE;
    }