Saturday, November 14, 2009

Finding child windows in c#

If you have a IntPtr window handle (e.g. by using Process.MainWindow), the following helper functions lets you find any of its child windows by class name and/or window title, recursively:

/// 
/// Uses FindWindowEx() to recursively search for a child window with the given class and/or title.
/// 
public static IntPtr FindChildWindow( IntPtr hwndParent, string lpszClass, string lpszTitle )
{
 return FindChildWindow( hwndParent, IntPtr.Zero, lpszClass, lpszTitle );
}


[DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);

/// 
/// Uses FindWindowEx() to recursively search for a child window with the given class and/or title.
/// 
public static IntPtr FindChildWindow( IntPtr hwndParent, string lpszClass, string lpszTitle )
{
 return FindChildWindow( hwndParent, IntPtr.Zero, lpszClass, lpszTitle );
}

/// 
/// Uses FindWindowEx() to recursively search for a child window with the given class and/or title,
/// starting after a specified child window.
/// If lpszClass is null, it will match any class name. It's not case-sensitive.
/// If lpszTitle is null, it will match any window title.
/// 
public static IntPtr FindChildWindow( IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszTitle )
{
 // Try to find a match.
 IntPtr hwnd = FindWindowEx( hwndParent, IntPtr.Zero, lpszClass, lpszTitle );
 if ( hwnd == IntPtr.Zero )
 {
  // Search inside the children.
  IntPtr hwndChild = FindWindowEx( hwndParent, IntPtr.Zero, null, null );
  while ( hwndChild != IntPtr.Zero && hwnd == IntPtr.Zero )
  {
   hwnd = FindChildWindow( hwndChild, IntPtr.Zero, lpszClass, lpszTitle );
   if ( hwnd == IntPtr.Zero )
   {
    // If we didn't find it yet, check the next child.
    hwndChild = FindWindowEx( hwndParent, hwndChild, null, null );
   }
  }
 }
 return hwnd;
}

2 comments: