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

By : shea241
Source: Stackoverflow.com
Question!

Kind of a special case problem:

  • I start a process with System.Diagnostics.Process.Start(..)
  • The process opens a splash screen -- this splash screen becomes the main window.
  • The splash screen closes and the 'real' UI is shown. The main window (splash screen) is now invalid.
  • I still have the Process object, and I can query its handle, module, etc. But the main window handle is now invalid.

I need to get the process's UI (or UI handle) at this point. Assume I cannot change the behavior of the process to make this any easier (or saner).

I have looked around online but I'll admit I didn't look for more than an hour. Seemed like it should be somewhat trivial :-(

By : shea241


Answers

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

For that you will need to use FindWindowEx

By : Ash


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 right pain, so hopefully there's a simpler way.

By : MB.


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());
}
By : Giova


This video can help you solving your question :)
By: admin