EnumDesktopWindows(C++)大约需要30分钟才能在Windows 10上找到所需的打开窗口

EnumDesktopWindows (C++) takes about 30 mins to find the desired open Window on Windows 10

本文关键字:Windows 开窗口 C++ 30分钟 EnumDesktopWindows      更新时间:2023-10-16

此问题仅在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 分钟内没有任何反应。未命中调试点。此时,原始正在运行的应用程序无响应。

如何解决这个问题?

找到了另一条路。而不是按窗口名称,查找进程帮助。使用进程名称获取进程,提取进程 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;
    }