3

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.

Simpom
  • 938
  • 1
  • 6
  • 23
  • While trying to find a solution, I found the following post giving a solution in VB: https://stackoverflow.com/a/34143777/3909303 – Simpom Feb 19 '19 at 15:42

2 Answers2

3

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).

Simpom
  • 938
  • 1
  • 6
  • 23
0

Application().connect can return a collection of windows.

Instead use app['YOUR TITLE HERE'] or use find_windows.

From there you can capture the image without those borders.

You can find more info from the docs.

סטנלי גרונן
  • 2,917
  • 23
  • 46
  • 68
Joseph Luce
  • 11
  • 1
  • 3