获取 WPF 进程中所有 windows 的句柄

Get handles of all windows in a WPF process

我知道我可以通过枚举 Process.GetProcesses 获取 MainWindowHandle,但我还想获取 WPF 应用程序可能具有的所有 WPF windows 的句柄。我需要在一个完全独立的过程中执行此操作。我该怎么做?谢谢

由于 WPF 进程有多个线程,您必须枚举所有线程才能找到 windows。

我使用了下面的 Win32 方法来做到这一点。您创建一个列表并添加到每次迭代调用的回调中的列表。

[DllImport("user32.dll")] 
public static extern bool EnumThreadWindows(int dwThreadId, EnumThreadWindowsCallBack lpfn, IntPtr lParam);

 Win32.EnumThreadWindows(processThread.Id, (hWnd, lParam) =>
                {
                    if (Win32.IsWindowVisible(hWnd))
                    {
                        Win32.RECT windowRect;
                        Win32.GetWindowRect(hWnd, out windowRect);

                        if (hWnd != _currentWindowHandle)
                        {
                            windowList.Add(new WindowInfo(hWnd, windowRect));
                        }
                    }
                    return true;
                }, IntPtr.Zero);