Can PyGetWindow help Screenshot?

853 views Asked by At

Can I use PyGetWindow to help pyautogui screenshot a specific window? If yes, how? Thanks.

1

There are 1 answers

0
tinus On

Yes you can make a screenshot of a specific window I'm using the new window and take in consideration that you have a color in mind to move cursor to for this example.

import os
import pygetwindow
import pyautogui

z1 = pygetwindow.getAllTitles()
time.sleep(1)
# open a file
os.startfile("C:\\Users\\name\\path")
time.sleep(1)
z2 = pygetwindow.getAllTitles()
# gets new window title 
z3 = [x for x in z2 if x not in z1]
z3 = ''.join(z3)
# activate new window
y = pygetwindow.getWindowsWithTitle(z3)[0]
y.activate()

color_locate = (220,220,220) # edit the color here

locations_of_color = []
s = pyautogui.screenshot()
s.save(r'C:\\Users\\user\\Pictures\\folder\\s.png')
for xx in range(s.width):
    for yy in range(s.height):
        if s.getpixel((xx, yy)) == color_locate:
            located_color = pyautogui.position(xx, yy)
            a = [i for i in located_color]
            locations_of_color.append(a)
    print(len(locations_of_color))
    time.sleep(3)
    # tries to move to middle 
    try:
        i = len(locations_of_color) // 2
        pyautogui.moveTo(locations_of_color[i])
    except:
        try:
            pyautogui.moveTo(locations_of_color[0])
        except:
            pyautogui.moveTo(locations_of_color)
time.sleep(3)

If you only want a screenshot use the top code ( till y.activate() ) then just do:

s = pyautogui.screenshot()
s.save(r'C:\\Users\\user\\Pictures\\folder\\s.png')