Search code examples
pythonpywin32

I'm not sure win32gui.EnumWindows is working properly


I'm just getting started with pywin32 so I'm slightly sketchy about how it's supposed to work in the first place, but win32gui.EnumWindows just doesn't like it when I return False from the callback and I'm not sure why. For instance, the following crashes

from win32gui import EnumWindows

def derp(hWnd, lParam):
    return False

EnumWindows(derp, 0)

with traceback

Traceback (most recent call last):
  File "C:\--------\test5.py", line 7, in <module>
    EnumWindows(ewp, 0)
error: (126, 'EnumWindows', 'The specified module could not be found.')

The error codes can vary, so I'm thinking they don't have anything to do with the EnumWindows call really. For instance, the code changes to 123 ('The filename, directory name, or volume label syntax is incorrect.') if I run it on my old XP laptop, and if I put a print statement before 'return False' it comes back as error 0. Everything works fine if I just return True from the callback every time and let it cycle through all windows.

My thought is that since the C version of EnumWindows returns false both when the callback returns false and when something genuinely goes wrong, the wrapper can only see the return value and assumes the worst whenever it gets false? Or is it something else?

(using python 2.7.9 and pywin32 build 219)


Solution

  • I think that EnumWindows is doing exactly what its documentation says it will do. Returning False from the callback function terminates the enumeration. Your statement "the wrapper can only sees the return value" means nothing, since according to the documentation this function isn't supposed to return anything. Why don't you forget about analyzing the return value and just wrap the call to EnumWindows in a try: except: block if you want to suppress the exception.