UiaControlsTest.TargetApp.TryFindWindowNow C# (CSharp) Method

TryFindWindowNow() private static method

private static TryFindWindowNow ( int pid, string className, string windowTitle ) : IntPtr
pid int
className string
windowTitle string
return System.IntPtr
        private static IntPtr TryFindWindowNow(int pid, string className, string windowTitle)
        {
            var hwnd = GetDesktopWindow();
            var hwndChild = GetWindow(hwnd, GW_CHILD);
            for (; hwndChild != IntPtr.Zero; hwndChild = GetWindow(hwndChild, GW_HWNDNEXT))
            {
                // Check for PID, if specfied (do first because it's quick)...
                if (pid != 0)
                {
                    int id;
                    GetWindowThreadProcessId(hwndChild, out id);
                    if (id != pid)
                    {
                        continue;
                    }
                }

                // ignore invisible worker windows...
                if (! IsWindowVisible(hwndChild))
                {
                    continue;
                }

                // ignore console windows...
                var testClassName = new StringBuilder(64);
                GetClassName(hwndChild, testClassName, 64);
                if (String.Compare(testClassName.ToString(), "ConsoleWindowClass", true) == 0)
                {
                    // It's a console window - ignore it
                    continue;
                }

                // Check classname, if specified...
                if (className != null)
                {
                    if (String.Compare(className, testClassName.ToString(), true, CultureInfo.InvariantCulture) != 0)
                        continue;
                }

                // Check title, if specified...
                if (windowTitle != null)
                {
                    var testWindowTitle = new StringBuilder(64);
                    GetWindowText(hwndChild, testWindowTitle, 64);
                    if (String.Compare(windowTitle, testWindowTitle.ToString(), true, CultureInfo.InvariantCulture) != 0)
                        continue;
                }

                // Matches all criteria - return it!
                return hwndChild;
            }
            return IntPtr.Zero;
        }