top of page

Enumerate all child windows

  • Writer: John
    John
  • 5 minutes ago
  • 2 min read
This post is one of a series providing implementation examples of Windows API Functions, Types, Enums and Consts using VBA. The code in this post can be used as-is, however, if you regularly (or even just occasionally) work with Windows API declarations in VBA, you may want to see the posts Automatically add Windows API declaration(s) and Using 'F1' to view Windows API web pages which explain some of the functionality that can be added to the VBE by VBE_Extras.

The EnumChildWindows Windows API Function enumerates all child windows of a (parent) window ... and it does so recursively in that all child windows of those child windows (ie so grandchild windows) are also enumerated, as are great-grandchild windows, great-great-grandchild windows and so on. This makes EnumChildWindows very handy if you want to get a list of all such windows, or if you want to get all such window(s) with a specific caption and/or class name.


The following code is an example implementation of using EnumChildWindows. The GetAllChildWindows VBA Function can be called by other code. It takes parameters of the parent window handle, filter criteria (for the window caption and/or class) and "returns" an array of child window handles plus a count of the number of windows found.


When EnumChildWindows is called, the address of a 'callback' Function is passed in. This 'callback' Function (named EnumChildProc in this example implementation) is called multiple times, once for each child window. It checks that the window caption and/or class match the filter criteria and, if so, adds the handle of the window to an array.


Here's the code. This must be added to a standard Module (due to the use of the VBA AddressOf operator).



And here's an example of using that code, in this case, just printing the window handle, caption and class name to the Immediate window ...



... of course, this code still needs to receive the handle for the parent window as its hWnd parameter ... so, here's another example of doing that for whichever window is the foreground window ...



... if you put the cursor in the Test Sub and press F5 then you will see details of all of the child (and grandchild, etc) windows of the VBE listed in the Immediate window. Of course, you can pass in any window handle that you want ... try passing in the handle for the host application (see post Get the application window handle in any app (well ... in Excel, Word, Access, PowerPoint or Outlook) if you're not sure how to get the handle) or you can use one of the many Windows API Functions that return a window handle such as FindWindow or FindWindowEx (see post Getting windows ... and getting information about windows ... using the Windows API for details on these two Functions, plus many more that will return a specific window handle).

bottom of page