private void EnumerateTopLevelWindows()

in sources/Google.Solutions.Platform/Dispatch/Win32Process.cs [73:117]


        private void EnumerateTopLevelWindows(Action<IntPtr> action)
        {
            bool callback(IntPtr hwnd, int _)
            {
                if (!NativeMethods.IsWindowVisible(hwnd))
                {
                    //
                    // Window is top-level, but hidden. Ignore.
                    //
                }
                else if (NativeMethods.GetWindowThreadProcessId(
                        hwnd,
                        out var ownerProcessId) != 0 &&
                    ownerProcessId == this.processId)
                {
                    //
                    // This window belongs to our process. 
                    //
                    action(hwnd);
                }

                //
                // NB. There might be more top-level windows, so continue
                // the search.
                //

                return true;
            }

            //
            // Enumerate all top-level windows.
            //
            // Ignore ERROR_INVALID_PARAMETER errors as those are expected
            // in non-interactive sessions.
            //
            if (!NativeMethods.EnumWindows(callback, IntPtr.Zero) &&
                Marshal.GetLastWin32Error() is int lastError &&
                (lastError != NativeMethods.ERROR_SUCCESS &&
                 lastError != NativeMethods.ERROR_INVALID_PARAMETER &&
                 lastError != NativeMethods.ERROR_INVALID_HANDLE))
            {
                throw DispatchException.FromLastWin32Error(
                    $"{this.imageName}: Enumerating windows failed");
            }
        }