[Python] pywin32 EnumWindows throws "The specified module could not be found" error on Windows...

Discussão em 'Python' iniciado por Stack, Dezembro 8, 2024.

  1. Stack

    Stack Membro Participativo

    I'm trying to write a Python script on Windows 10 that finds a window by its title and then moves/resizes it using pywin32. I have the following code:

    import win32gui

    # Global variables
    found_hwnd = None
    partial_title = None # We'll set this before calling EnumWindows

    def enum_windows_callback(hwnd, lParam):
    global found_hwnd, partial_title
    if win32gui.IsWindowVisible(hwnd):
    window_title = win32gui.GetWindowText(hwnd)
    if partial_title and partial_title.lower() in window_title.lower():
    found_hwnd = hwnd
    # Returning False stops the enumeration
    return False
    # Continue enumerating
    return True

    def find_window_by_title(title_substring):
    global found_hwnd, partial_title
    found_hwnd = None
    partial_title = title_substring
    win32gui.EnumWindows(enum_windows_callback, None)
    return found_hwnd

    def move_and_resize_window(hwnd, x, y, width, height):
    if hwnd is None:
    print("No valid window handle provided.")
    return False
    win32gui.MoveWindow(hwnd, x, y, width, height, True)
    return True

    if __name__ == "__main__":
    # Example usage:
    hwnd = find_window_by_title("Cha")

    if hwnd:
    print(f"Found window with HWND: {hwnd}")
    success = move_and_resize_window(hwnd, 100, 100, 800, 600)
    if success:
    print("Window moved and resized successfully.")
    else:
    print("Failed to move and resize the window.")
    else:
    print("No window found containing 'Notepad' in its title.")



    When running the above code, sometimes I get an error:


    pywintypes.error: (126, 'EnumWindows', 'The specified module could not be found.')
    ​

    This happens when I try to find a known window by title. Strangely, if I look for a title that doesn't exist, it exits cleanly with "No window found." But for certain existing windows, it throws the error.

    What could cause EnumWindows to throw "The specified module could not be found" (error 126) intermittently when using pywin32? Is there something about the environment, the way the callback is structured, or pywin32 setup that I’m missing?

    Any insights or troubleshooting steps would be greatly appreciated.

    What I've tried:

    • Reinstalling pywin32 using pip install --upgrade pywin32
    • Ensuring the callback function is defined at the top level, not nested
    • Running the script as an Administrator
    • Checking that I'm using the same Python interpreter environment for both the test script and the main script
    • Confirming pywin32 is compatible with my Python (e.g., both 64-bit)

    Continue reading...

Compartilhe esta Página