Search code examples
apiwinapifindwindowfindwindowex

How to find a child HWND of a child window of a child window (3 levels deep) with Win32 API?


Suppose I've this Window hierarchy for one of the processes:

Main Window               (class name: XYZ_Widget_1)
`- Child Window           (class name: XYZ_Widget_0)
  `- Child-Child Window    (class name: XYZ_Renderer)

How do I find the HWND of the Child-Child Window?

I tried using FindWindow Win32 API function on XYZ_Renderer class but the FindWindow function doesn't find child windows.

Then I tried using FindWindow to find Main Window, which succeeded, but after that using FindWindowEx can only find Child Window as Child-Child Window is not a child of Main Window.

I guess I could go one layer deeper and call FindWindowEx on the Child Window once it's found.

But before I do that I figured maybe there is an easy way to find Child-Child Window?


Solution

  • You have to call FindWindowEx() for each child level that you want to go down, specifying the HWND found in the previous level as the parent, eg:

    HWND hWnd = FindWindow("XYZ_Widget_1", NULL);
    if (hWnd != NULL)
    {
        hWnd = FindWindowEx(hWnd, NULL, "XYZ_Widget_0", NULL);
        if (hWnd != NULL)
        {
            hWnd = FindWindowEx(hWnd, NULL, "XYZ_Renderer", NULL);
            // and so on... 
        }
    }
    

    There is no simplier way to do it. To simplify your code, you could write your own function that accepts a path of class/window names as input, looping through it calling FindWindow/Ex() for each leg as needed.