There are multiple ways to do that. The code for these will require modification based on your needs, so I will put in some pointers to the high level methods and libraries:

  1. You can directly use GUI-automation tools such as pyautogui to press Alt+PrntScreen and transfer the data from clipboard into a variable (http://pyautogui.readthedocs.io/en/latest/keyboard.html#keyboard-keys)

  2. You can use pywin32 and PIL to grab the image of a certain window (How to Get a Window or Fullscreen Screenshot (without PIL)?)

  3. You can use ImageMagick to grab screenshots of a single window (https://www.imagemagick.org/discourse-server/viewtopic.php?t=24702)

  4. You can use pyautogui.locateOnScreen("Sceenshot.PNG") to find the tuple which will contain the boundaries of the window for your java app. Then you can pass it to your function img.ImageGrab.grab(bbox)

Answer from alpha_989 on Stack Overflow
Top answer
1 of 3
33

There are multiple ways to do that. The code for these will require modification based on your needs, so I will put in some pointers to the high level methods and libraries:

  1. You can directly use GUI-automation tools such as pyautogui to press Alt+PrntScreen and transfer the data from clipboard into a variable (http://pyautogui.readthedocs.io/en/latest/keyboard.html#keyboard-keys)

  2. You can use pywin32 and PIL to grab the image of a certain window (How to Get a Window or Fullscreen Screenshot (without PIL)?)

  3. You can use ImageMagick to grab screenshots of a single window (https://www.imagemagick.org/discourse-server/viewtopic.php?t=24702)

  4. You can use pyautogui.locateOnScreen("Sceenshot.PNG") to find the tuple which will contain the boundaries of the window for your java app. Then you can pass it to your function img.ImageGrab.grab(bbox)

2 of 3
8

A example to get the content(screenshot) of a specific window with the help of the pygetwindow module.

import pygetwindow
import time
import os
import pyautogui
import PIL

# get screensize
x,y = pyautogui.size()
print(f"width={x}\theight={y}")

x2,y2 = pyautogui.size()
x2,y2=int(str(x2)),int(str(y2))
print(x2//2)
print(y2//2)

# find new window title
z1 = pygetwindow.getAllTitles()
time.sleep(1)
print(len(z1))
# test with pictures folder
os.startfile("C:\\Users\\yourname\\Pictures")
time.sleep(1)
z2 = pygetwindow.getAllTitles()
print(len(z2))
time.sleep(1)
z3 = [x for x in z2 if x not in z1]
z3 = ''.join(z3)
time.sleep(3)

# also able to edit z3 to specified window-title string like: "Sublime Text (UNREGISTERED)"
my = pygetwindow.getWindowsWithTitle(z3)[0]
# quarter of screen screensize
x3 = x2 // 2
y3 = y2 // 2
my.resizeTo(x3,y3)
# top-left
my.moveTo(0, 0)
time.sleep(3)
my.activate()
time.sleep(1)

# save screenshot
p = pyautogui.screenshot()
p.save(r'C:\\Users\\yourname\\Pictures\\\\p.png')

# edit screenshot
im = PIL.Image.open('C:\\Users\\yourname\\Pictures\\p.png')
im_crop = im.crop((0, 0, x3, y3))
im_crop.save('C:\\Users\\yourname\\Pictures\\p.jpg', quality=100)

# close window
time.sleep(1)
my.close()
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ how i can screenshot a specific window?
r/learnpython on Reddit: How i can screenshot a specific window?
August 12, 2021 -

First time posting here, i am very new to python, but i want to make a screenshot of a specific window, instead of all of the screen, this is my current code that makes a screenshot of all of the screen

from PIL import ImageGrab
screen =  ImageGrab.grab(bbox=(0,0,1366,768))
screen.save('grabbed.png')
print("done")

I searched on internet but the only solution that i found was to get the size and position of the selected window and then take a screenshot with those info so it only gets that window, howewer if there is something covering that window it wont take the screenshot correctly... is it atleast possible?

Discussions

How to take a screenshot/screen capture of a specific window?
I'm looking for a way to capture screen shots/screen captures. I'm basically looking for the functionality offered by imagemagick's import tool. I went over the example code but didn... More on github.com
๐ŸŒ github.com
3
December 24, 2016
MacOS: Using python to capture screenshots of a specific ...
I am using MSS to capture the screenshot of my screen. (Because it captures faster screenshots) But I am not sure how to go about capturing a specific window in Mac, I know they have win32 for Wind... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Get screenshot on Windows with Python? - Stack Overflow
I am creating a Beta Testers reporting module so they can send in thier comments on my software, but I would like to have the option to include a screenshot with the report. How do I take a screenshot of the screen with Python on Windows? More on stackoverflow.com
๐ŸŒ stackoverflow.com
How i can screenshot a specific window?
I may have made exactly what you're looking for. With a tkinter interface. The window has to be active unfortunately but this tool does that for you. Should grab all of the same type of window, as in take a screenshot of each pdf open for example... Windows cannot be minimized if I remember correctly. https://github.com/Reuben3901/Windows_Window_Screenshot/blob/master/WindowScreenshotButtons.py More on reddit.com
๐ŸŒ r/learnpython
7
6
August 12, 2021
๐ŸŒ
PyAutoGUI
pyautogui.readthedocs.io โ€บ en โ€บ latest โ€บ screenshot.html
Screenshot Functions โ€” PyAutoGUI documentation
>>> import pyautogui >>> im = pyautogui.screenshot(region=(0,0, 300, 400)) NOTE: As of version 0.9.41, if the locate functions canโ€™t find the provided image, theyโ€™ll raise ImageNotFoundException instead of returning None.
๐ŸŒ
GitHub
github.com โ€บ python-xlib โ€บ python-xlib โ€บ issues โ€บ 71
How to take a screenshot/screen capture of a specific window? ยท Issue #71 ยท python-xlib/python-xlib
December 24, 2016 - I'm looking for a way to capture screen shots/screen captures. I'm basically looking for the functionality offered by imagemagick's import tool. I went over the example code but didn't see anything that was capturing screen shots. I was ...
Author ย  devonhk
๐ŸŒ
LearnCodeByGaming
learncodebygaming.com โ€บ blog โ€บ fast-window-capture
Fast Window Capture - LearnCodeByGaming.com
May 28, 2020 - Firstly, we approach the theoretical limit for how fast we can take these screenshots by dealing right with the operating system itself. Secondly, the Windows API has methods that will allow us to grab the screen data for only the window we're interested in, even when it's minimized or off screen. To do this, we must first pip install pywin32 to get access to the Win32 API in Python.
๐ŸŒ
PyPI
pypi.org โ€บ project โ€บ wscreenshot
wscreenshot
September 21, 2020 - JavaScript is disabled in your browser. Please enable JavaScript to proceed ยท A required part of this site couldnโ€™t load. This may be due to a browser extension, network issues, or browser settings. Please check your connection, disable any ad blockers, or try using a different browser
๐ŸŒ
Medium
mgregchi02.medium.com โ€บ take-screenshots-of-any-area-of-the-screen-with-python-gui-program-6320110e99f7
Take screenshots of any area of the screen with python GUI program. | by Michael Amadi | Medium
December 6, 2020 - If he clicks โ€œscreenshotโ€ button, the window is hidden to avoid blocking the area for screenshot, and our screenshot function is called and the window is refreshed to get current location and size. Then some calculations is done to know where the user chose for screenshot then the screenshot image is returned. Line 71 to 75, the generic naming is prepared. All files with the specified name are compared to see if the next naming might conflict and if it wonโ€™t, then, drop our screenshot there with that pretty name.
Find elsewhere
๐ŸŒ
CodingFleet
codingfleet.com โ€บ transformation-details โ€บ python-code-to-screenshot-a-specific-window
How to Screenshot a Specific Window in Python - CodingFleet
Created at using the Python Code Generator tool. ... Although these codes and explanations are generated by AI tools, they are manually reviewed for accuracy and work most of the time.
๐ŸŒ
Python Forum
python-forum.io โ€บ thread-14328.html
Screenshot of specific window
Hi, I have a program that needs to take an image of a small section of another program at 29.97 fps. Currently I'm using mss and manually specifying coordinates on the screen. I'm trying to figure out a way to do this automatically, preferably not n...
๐ŸŒ
YouTube
youtube.com โ€บ watch
Screenshot a specific window using Python in Windows / macOS - YouTube
The video describes how to take a screenshot of a specific window using Python.1. Use pyautogui to take a generic screenshot2. Get the dimensions of the desi...
Published ย  August 13, 2022
Top answer
1 of 3
4
import cv2 as cv
import numpy as np
from time import time
from mss import mss
from Quartz import CGWindowListCopyWindowInfo, kCGNullWindowID, kCGWindowListOptionAll
import Quartz

windowName = "Window Name like the name written on top of the window"


def get_window_dimensions(hwnd):
    window_info_list = Quartz.CGWindowListCopyWindowInfo(Quartz.kCGWindowListOptionIncludingWindow, hwnd)

    for window_info in window_info_list:
        window_id = window_info[Quartz.kCGWindowNumber]
        if window_id == hwnd:
            bounds = window_info[Quartz.kCGWindowBounds]
            width = bounds['Width']
            height = bounds['Height']
            left = bounds['X']
            top = bounds['Y']
            return {"top": top, "left": left, "width": width, "height": height}

    return None


def window_capture():
    loop_time = time()
    windowList = CGWindowListCopyWindowInfo(
        kCGWindowListOptionAll, kCGNullWindowID)

    for window in windowList:
        print(window.get('kCGWindowName', ''))
        if windowName.lower() in window.get('kCGWindowName', '').lower():
            hwnd = window['kCGWindowNumber']
            print('found window id %s' % hwnd)

    monitor = get_window_dimensions(hwnd)

    with mss() as sct:
        # monitor = {"top": 40, "left": 0, "width": 800, "height": 600}

        while (True):

            screenshot = np.array(sct.grab(monitor))
            screenshot = cv.cvtColor(screenshot, cv.COLOR_RGB2BGR)

            cv.imshow('Computer Vision', screenshot)

            print('FPS {}'.format(1 / (time() - loop_time)))
            loop_time = time()

            if cv.waitKey(1) == ord('q'):
                cv.destroyAllWindows()
                break


window_capture()

print('Done.')

A solution for the problem for macos, its easy to find the answer for windows but not so for mac. So here's the code folks. Solid 40fps... If you do the same by cv2 or pyautogui, it gives 5fps.

2 of 3
3

I wrote the following piece of ObjectiveC that gets the names, owners, window id and position on screen of all the windows in macOS. I saved it as windowlist.m and compiled it with the commands in the comments at the top of the file:

////////////////////////////////////////////////////////////////////////////////
// windowlist.m
// Mark Setchell
//
// Get list of windows with their characteristics
//
// Compile with:
// clang windowlist.m -o windowlist -framework coregraphics -framework cocoa
//
// Run with:
// ./windowlist
//
////////////////////////////////////////////////////////////////////////////////
#include <Cocoa/Cocoa.h>
#include <CoreGraphics/CGWindow.h>

int main(int argc, char **argv)
{
   NSArray *windows = (NSArray *)CGWindowListCopyWindowInfo(kCGWindowListOptionOnScreenOnly,kCGNullWindowID);
   for(NSDictionary *window in windows){
      int WindowNum = [[window objectForKey:(NSString *)kCGWindowNumber] intValue];
      NSString* OwnerName = [window objectForKey:(NSString *)kCGWindowOwnerName];
      int OwnerPID = [[window objectForKey:(NSString *) kCGWindowOwnerPID] intValue];
      NSString* WindowName= [window objectForKey:(NSString *)kCGWindowName];
      CFDictionaryRef bounds = (CFDictionaryRef)[window objectForKey:(NSString *)kCGWindowBounds];
      CGRect rect;
      CGRectMakeWithDictionaryRepresentation(bounds,&rect);
      printf("%s:%s:%d:%d:%f,%f,%f,%f\n",[OwnerName UTF8String],[WindowName UTF8String],WindowNum,OwnerPID,rect.origin.x,rect.origin.y,rect.size.height,rect.size.width);
   }
}

It gives output like this, where the last 4 items on each line are the window top-left corner, height and width. You can either run this program "as is" with Python's subprocess.Popen() and get the window list, or you could maybe convert it to Python using PyObjc Python module:

Location Menu:Item-0:4881:1886:1043.000000,0.000000,22.000000,28.000000
Backup and sync from Google:Item-0:1214:8771:1071.000000,0.000000,22.000000,30.000000
Dropbox:Item-0:451:1924:1101.000000,0.000000,22.000000,28.000000
NordVPN IKE:Item-0:447:1966:1129.000000,0.000000,22.000000,26.000000
PromiseUtilityDaemon:Item-0:395:1918:1155.000000,0.000000,22.000000,24.000000
SystemUIServer:AppleTimeMachineExtra:415:1836:1179.000000,0.000000,22.000000,40.000000
SystemUIServer:AppleBluetoothExtra:423:1836:1219.000000,0.000000,22.000000,30.000000
SystemUIServer:AirPortExtra:409:1836:1249.000000,0.000000,22.000000,30.000000
SystemUIServer:AppleVolumeExtra:427:1836:1279.000000,0.000000,22.000000,30.000000
SystemUIServer:BatteryExtra:405:1836:1309.000000,0.000000,22.000000,67.000000
SystemUIServer:AppleClockExtra:401:1836:1376.000000,0.000000,22.000000,123.000000
SystemUIServer:AppleUser:419:1836:1499.000000,0.000000,22.000000,99.000000
Spotlight:Item-0:432:1922:1598.000000,0.000000,22.000000,36.000000
SystemUIServer:NotificationCenter:391:1836:1634.000000,0.000000,22.000000,46.000000
Window Server:Menubar:353:253:0.000000,0.000000,22.000000,1680.000000
Dock:Dock:387:1835:0.000000,0.000000,1050.000000,1680.000000
Terminal:windowlist โ€” -bash โ€” 140ร—30:4105:6214:70.000000,285.000000,658.000000,1565.000000
๐ŸŒ
YouTube
youtube.com โ€บ watch
GRAB SCREENSHOTS WITH PYTHON EVERY 5 SECONDS (TUTORIAL) - YouTube
I'll show you how you can grab screenshots with Python every 5 seconds. Another fun beginner project to learn Python.๐Ÿ“š MY FAVOURITE PROGRAMMING BOOKS ๐Ÿ“šPyth...
Published ย  February 27, 2021
๐ŸŒ
GitHub
github.com โ€บ ra1nty โ€บ DXcam
GitHub - ra1nty/DXcam: A Python high-performance screen capture library for Windows using Desktop Duplication API - Updated 2026 ยท GitHub
3 weeks ago - DXcam is a high-performance python screenshot and capture library for Windows based on the Desktop Duplication API. It is designed for low-latency, high-FPS capture pipelines (including full-screen Direct3D applications). Compared with common Python alternatives, DXcam focuses on: ... Seamless integration for AI Agent / Computer Vision use cases. ... Official Windows wheels are built for CPython 3.10 to 3.14.
Starred by 695 users
Forked by 94 users
Languages ย  Python 90.3% | Cython 9.7%
๐ŸŒ
YouTube
youtube.com โ€บ watch
How to screenshot a specific window - WITHOUT using the snipping tool ๐Ÿš€ - YouTube
Do you ever need to capture a specific window to use in maybe a work document, or tutorial manual?Sure, you can use the snipping tool, but in this quick vide...
Published ย  December 22, 2024
๐ŸŒ
Scrapfly
scrapfly.io โ€บ blog โ€บ posts โ€บ how-to-take-screenshots-in-python
How To Take Screenshots In Python? - Scrapfly Blog
August 8, 2024 - For instance, by emulating a specific phone browser, the website screenshot taken appears as if it was captured by an actual phone. Viewport settings represent the resolution of the browser device through width and height dimensions. Here's how to change Python screenshot viewport: ... # .... # set the viewport dimensions (width x height) driver.set_window_size(1920, 1080) driver.get("https://web-scraping.dev/products") driver.save_screenshot("products.png")
๐ŸŒ
Medium
pythonflood.com โ€บ python-project-take-screenshot-using-pyscreenshot-3cfceea0e7ba
Python Project- Take Screenshot using pyscreenshot | by Rinu Gour | PythonFlood
November 11, 2023 - Itโ€™s a common need to take a screenshot while using a computer. Sometimes, screenshots referred as a screengrab, is an image that shows the contents of a computer display. Screenshot captures exactly what you are seeing on screen. In this Project we are making a simple app with Python that will capture a screenshot of the pc screen.
๐ŸŒ
YouTube
youtube.com โ€บ shorts โ€บ MgxHE3E_m6w
Taking Screenshots With Python | Python Tutorial - YouTube
In this video I show you how to take a screenshot in Python using the pyautogui library.#coding #pythontutorial #pythonforbeginners #python #100daysofpython ...
Published ย  June 7, 2024