I don't conceptually understand what I am supposed to do for the second parameter of EnumChildWindows()
. The API reference assumes more knowledge/experience than I have (I am an amateur), and reading about callback functions did not help my understanding. Can someone explain?
What I want to do is get a Python list of child HWND
s, which I can then iterate through to find a particular window/control to read its text. I have put together code that can do this second part, but that only works if I give it a hard-coded child HWND
, which is what I am trying to automate here.
I am using Python 3.11 and the win32api
module.
hwnd = win32gui.FindWindow(None, window_title_text)
child_windows = []
win32gui.EnumChildWindows(hwnd , ???, child_windows)
The second parameter to your function is a callback function (or, as it's known in the C/C++ world, a function pointer) that takes 2 arguments as parameters.
The first one being an HWND
, and the second one being the other object/pointer that you pass as the third parameter to EnumChildWindows()
.
If you call EnumChildWindows()
with a NULL HWND
, it will enumerate all windows in your system, eg:
EnumChildWindows(0, function_pointer, "my_value")
My implementation to your problem is as follows:
from win32gui import EnumChildWindows, GetWindowText
my_target_hwnd = 0
def function_pointer(child_hwnd, target_name):
global my_target_hwnd
name = GetWindowText(child_hwnd)
if target_name in name:
my_target_hwnd = child_hwnd
# Iteration stops when you return False
return False
EnumChildWindows(0, function_pointer, "python")
if my_target_hwnd == 0:
print("window not found")
exit()
print(f"found window with hwnd '{my_target_hwnd}'")