Search code examples
pythonwinapipywin32

Trying to find a ListBox in order to send messages to it


I'm trying to send a message (LB_SELECTSTRING) to a ListBox control inside a (child) window using pywin32. I've gotten the handle to the window without issue, and I also have the thread id and process id of the parent window. My understanding is that controls are treated similarly to windows in that they have their own handles, so I'm trying to figure out how to find the control using its parents handle and nothing seems to work.

The code I have is below and it always raises an exception.

try:
    _listbox1_hwnd = win32gui.FindWindowEx(_hwnd, None, "ListBox1", "Preferences")
    if _listbox1_hwnd == 0:
        raise Exception("Listbox1 wasn't found!")
except Exception as e:
    print e
    sys.exit(0)

I've also tried using the win32ui FindWindow method with no luck (ie this also fails)

try:
    _listbox1_cwnd = win32ui.FindWindow("ListBox1", "Preferences")
    if _listbox1_cwnd == 0:
        raise Exception("Listbox1 wasn't found!")
except Exception as e:
    print e
    sys.exit(0)

Solution

  • If you find Python language easier, why not use pywinauto? I never saw easier automation tool. And it's very pythonic.