Search code examples
pythonpython-3.xpywinauto

pywinauto capture_as_image adds unwanted borders


I am using pywinauto to take a screenshot of a specific window.

Here is the code I use to take a capture of notepad ("Bloc-notes" in french) :

from pywinauto import Application
app = Application().connect(title_re=".*Bloc-notes")
hwin = app.top_window()
hwin.set_focus()
img = hwin.capture_as_image()
img.save('notepad_screenshot.png')

And here is the result:

screenshot

The red "border" is the background of the window. How can I safely eliminate this red border?

I tried to configure Windows 10 in order not to show windows shadows (in the "visual effects settings") but it has no effect on the size of the capture.

When I look precisely on the capture, I can see that the left, bottom and right borders are 7 pixels thick. Can I reliably remove these pixels? What I mean by "reliably" is: will it always work, and work on other computers?

Any help appreciated.


Solution

  • Here is the solution I found.

    import ctypes
    from pywinauto import Application
    import win32gui
    
    app = Application().connect(title_re=".*Bloc-notes")
    hwin = app.top_window()
    hwin.set_focus()
    
    window_title = hwin.window_text()
    rect = ctypes.wintypes.RECT()
    DWMWA_EXTENDED_FRAME_BOUNDS = 9
    ctypes.windll.dwmapi.DwmGetWindowAttribute(
        ctypes.wintypes.HWND(win32gui.FindWindow(None, window_title)),
        ctypes.wintypes.DWORD(DWMWA_EXTENDED_FRAME_BOUNDS),
        ctypes.byref(rect),
        ctypes.sizeof(rect)
    )
    
    img = hwin.capture_as_image(rect)
    img.save('notepad_screenshot_ok.png')
    

    And here is the result:

    enter image description here

    It has worked on all the tests I run (different windows).