.NET (C#): Getting child windows when you only have a process handle or PID?

Solution 1:

If you don't mind using the Windows API, you could use EnumWindowsProc, and check each of the handles that that turns up using GetWindowThreadProcessId (to see that it's in your process), and then maybe IsWindowVisible, GetWindowCaption and GetWindowTextLength to determine which hWnd in your process is the one you want.

Though if you haven't used those functions before that approach will be a real pain, so hopefully there's a simpler way.

Solution 2:

@ageektrapped is on the right track, however FindWindow will not search child windows.

For that you will need to use FindWindowEx

Solution 3:

Thank you for your answers. Thanks to you here, I figured out how to know if the main window of a process is in front or not:

N.B : of course this needs System.Diagnostic and System.Runtime.Interrop

public bool IsWindowActive(Int32 PID)
{
  return IsWindowActive(Process.GetProcessById(PID));
}

[DllImport("user32.dll")]
private static extern
IntPtr GetForegroundWindow();

public bool IsWindowActive(Process proc)
{
  proc.Refresh();
  return proc.MainWindowHandle.Equals(GetForegroundWindow());
}

Solution 4:

You may find that if you call .Refresh() that you get the new top-level window.