Search code examples
pythonwin32guipyautogui

unable to capture window title python


The following code snippet should look for a window "Notes.txt - Notepad" and capture a screen-shot of that window.

import pyautogui
import win32gui

def screenshot(window_title="Notes.txt - Notepad"):
    if window_title:
        hwnd = win32gui.FindWindow(window_title, None)
        if hwnd:
            win32gui.SetForegroundWindow(hwnd)
            x, y, x1, y1 = win32gui.GetClientRect(hwnd)
            x, y = win32gui.ClientToScreen(hwnd, (x, y))
            x1, y1 = win32gui.ClientToScreen(hwnd, (x1 - x, y1 - y))
            im = pyautogui.screenshot(region=(x, y, x1, y1))
            return im
        else:
            print('Window not found!')
    else:
        im = pyautogui.screenshot()
        return im


im = screenshot('Calculator')
if im:
    im.show()

The issues here is that no matter what I pass as window_title it always return:

Window not found!

When I print(hwnd) it evaluate to 0

File title: enter image description here


Solution

  • The issue lies here - hwnd = win32gui.FindWindow(window_title, None).

    Replace it with win32gui.FindWindowEx(None, None, None, window_title) and it should work.

    Docs

    EDIT:

    win32gui.FindWindow(None, window_title) should also work.