The right Python method depends on your operating system. A real window capture asks the OS for that window’s surface; a region capture merely copies the pixels currently visible in a rectangle. On Windows, evaluate Pillow’s ImageGrab.grab(window=...) or use the native Windows.Graphics.Capture picker. On macOS, ScreenCaptureKit can filter one shareable window, but Python requires a bridge. On Linux, the XDG Desktop Portal can ask the user to select a window. If a visible, unobscured crop is sufficient, MSS or PyAutoGUI is simpler.
Choose the capture model first
Before installing a package, decide whether you need the window itself or only what is visible on screen.
| Requirement | Best starting point | What it really captures |
|---|---|---|
| One Windows application window selected by the user | Windows.Graphics.Capture | A native application-window or display stream, selected through secure system UI. |
| One macOS shareable window | ScreenCaptureKit | A desktop-independent window supplied to an SCContentFilter; a Python binding or bridge is still required. |
| Linux window chosen in a desktop dialog | XDG Desktop Portal Screenshot | A portal request with a window target, subject to the installed portal and backend. |
| Known coordinates and a visible window | MSS region capture or PyAutoGUI | Current screen pixels in a rectangle; occluded, minimized or moved windows are not recovered. |
| A direct Python call worth evaluating on Windows | Pillow ImageGrab | Its documented window argument is intended to capture one window; verify behavior with your installed Pillow and Windows version. |
There is no single Python call with identical behavior on all three desktop platforms. Permissions, compositor behavior, virtual desktops, remote sessions and application-specific protected content can change the result.
Windows: try Pillow’s window capture carefully
Pillow exposes ImageGrab.grab(window=...) in its reference API. The difficult part is obtaining the correct native window handle (HWND). Pillow’s reference does not provide a universal title-to-HWND workflow, so treat this as an environment-specific entry point rather than a promise that every Pillow release supports every Windows session.
#1 Best Overall
- Spacious Design: Measuring 21.1" wide and 14.1" deep, our lap desk comfortably fits most laptops up to 15.6". Extra room for accessories ensures convenience.
- Enhanced Functionality: Packed with handy features, including a 5x9" precision tracking mouse pad and a built-in phone slot for seamless work or video calls. Plus, enjoy ergonomic support with the integrated cushioned wrist rest.
- Cool Comfort: Enjoy a stable surface with our lap desk's dual bolster cushion, designed for comfort and airflow, keeping your lap cool during extended use.
- Durable Surface: Work with confidence on our lap desk's solid surface, featuring a sleek black carbon color, ensuring optimal air circulation to prevent your laptop from overheating.
- On-the-Go Convenience: With an integrated handle and lightweight design (2.8 lbs), our lap desk is portable for travel or moving around the house, offering flexibility in any space.
Minimal capture with a known HWND
from pathlib import Path
from PIL import ImageGrab
# Replace this with the integer HWND returned by your window-discovery code.
hwnd = 123456
if not isinstance(hwnd, int) or hwnd <= 0:
raise ValueError("hwnd must be a positive Windows window handle")
try:
image = ImageGrab.grab(window=hwnd)
except TypeError as exc:
raise RuntimeError(
"This installed Pillow does not accept window=; check its version and Windows support."
) from exc
except OSError as exc:
raise RuntimeError(
"Windows could not capture that window. Check that it exists and is permitted."
) from exc
output = Path("window.png")
image.save(output)
print(f"Saved {output.resolve()} ({image.width}x{image.height})")
The example deliberately does not pretend that a title is a handle. A discovery layer must enumerate windows, discard invisible or destroyed handles, and deal with duplicate titles. If the target disappears between discovery and capture, report that failure and ask the user to choose again. Test minimized and covered windows separately: a library may return an error, an empty image or behavior that differs by Windows build.
Native Windows.Graphics.Capture
Microsoft’s Windows.Graphics.Capture workflow acquires frames from a display or application window. Its documented user flow invokes GraphicsCapturePicker, which displays secure system UI. Windows also draws a yellow notification border around the actively captured item. This is the strongest Windows route when user-mediated selection is acceptable, but the guide is for Windows app development rather than a ready-made Python package. A Python implementation therefore needs an appropriate Windows binding, a compiled extension, or a small native helper and an IPC boundary.
macOS: ScreenCaptureKit and permissions
ScreenCaptureKit explicitly models shareable displays, applications and windows. The native sequence is to call SCShareableContent.excludingDesktopWindows(...), locate the desired window, then construct SCContentFilter(desktopIndependentWindow: window) so the stream contains one window rather than the whole desktop.
Rank #2
- 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
- Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
- Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
- HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
- What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
Apple’s sample is Swift, not Python. In Python you must select and maintain a binding or bridge to the framework, convert the delivered video frame into an image, and handle macOS Screen Recording permission. The permission can be denied even when your code is correct; your program should surface a clear instruction to enable the application in System Settings before retrying.
The Tool Desk
Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →macOS implementation checklist
- Enumerate shareable windows instead of assuming a window title is unique.
- Exclude desktop windows when appropriate, as the native sample does.
- Keep the content filter tied to the selected window object; recreate it if the window closes.
- Expect permission failures and user cancellation.
- Do not claim that a minimized or protected window will always produce pixels; verify the target application and macOS release.
Linux: use the XDG Desktop Portal when selection matters
The XDG Desktop Portal Screenshot interface is a D-Bus desktop service designed for application-mediated capture. Its request has a target option: screen (1), user-selected window (2), area (4) and, in interface versions that support it, active window (8). The portal implementation and backend determine which targets are advertised on a particular desktop.
A Python client must create the D-Bus request, listen for the response signal, handle a user cancellation, and then retrieve the returned image or URI according to the portal response. Check the installed portal interface version and backend instead of assuming that target 2 exists. This approach is preferable for sandboxed applications because the desktop controls what is shared.
Rank #3
- Note: Not suitable for MacBooks released after 2023 or devices with a protruding front camera; Not applicable to full-screen or notch-style tempered glass screen protectors; Do not use on the rear camera of the phone.
- 💻 Why Do You Need a Webcam Cover Slide? — Safeguard your privacy by covering your webcam with our reliable webcam cover when not in use. Don't let anyone secretly watch you. Stay protected!
- ✅ Thin & Stylish — Enhance your laptop's functionality and aesthetics with our 0.027" ultra-thin webcam covers. Seamlessly close your laptop while adding a touch of sophistication.
- ✅ Fits Most Devices — Compatible with laptops, phones, tablets, desktops! Keep your privacy intact on Ap/ple, Mac/Book, iPh/one, iP/ad, H/P, L/novo, De/ll, Ac/er, As/us, Sa/msung devices.
- ✅ 365 Days Protection — Our upgraded 3.0 adhesive ensures a strong hold that won't damage your equipment. Experience reliable, long-term privacy protection day in and day out.
Visible-window crop with MSS or PyAutoGUI
When a rectangle is enough, capture screen coordinates. MSS documents monitor and region inputs; PyAutoGUI’s screenshot function returns an image and can save it to a filename. Neither library, by itself, proves that a rectangle belongs to a window or finds a window by title.
MSS example
import mss
from PIL import Image
# Coordinates are screen pixels. Include negative values for monitors left of the primary display.
left, top, width, height = 100, 100, 900, 700
if width <= 0 or height <= 0:
raise ValueError("width and height must be positive")
with mss.mss() as sct:
shot = sct.grab({"left": left, "top": top,
"width": width, "height": height})
image = Image.frombytes("RGB", shot.size, shot.rgb)
image.save("visible-window-crop.png")
PyAutoGUI example
import pyautogui
left, top, width, height = 100, 100, 900, 700
image = pyautogui.screenshot(region=(left, top, width, height))
image.save("visible-window-crop.png")
Move or resize the target during capture and the crop can contain the wrong pixels. A second window covering part of it will be included. Minimized windows have no visible rectangle to copy. To make this reliable, obtain bounds from a platform window manager, validate them immediately before capture, and coordinate the capture with the application’s own UI.
Common failures and fixes
The image is black, blank or partly missing
Protected video, permission restrictions, a compositor limitation or a window that is no longer visible can produce this result. Test the same target with the native OS picker, grant Screen Recording permission on macOS, and distinguish a true window capture from a screen crop.
Rank #4
- Anti-Slip Surface - Transform your laptop into a mobile workstation with the AboveTEK portable laptop lap desk. The anti-slip surface provides a strong grip for laptops up to 15.6 inches(Diagonal), while the double rubber strip on the bottom ensures a stable display or typing experience on your lap, couch, or bed.
- Retractable Mouse Pad - Retractable laptop mouse pad extends on both directions for the left/right handed with elevation along the edges for stopping mouse from falling off. The size of laptop tray is 14" X 9.7" and the size of mouse pad is 7.4" X 6.1".
- Effective Heat Shield - The effective heat shield made of sturdy and thick material protects your laptop from overheating. Prioritizes your comfort and safety, an ideal lap pad or board for working anywhere.
- EASY to Carry and Store - With an ergonomic and simplistic design, the lap desk is portable to store in a backpack. Only 15" in size, 2.2 lb of weight and with slim 0.6 inch thickness, it is ready to be easily carried around.
- Widely Applicable - The smooth platform accommodates laptops and tablets up to 15.6 inches(Diagonal), making it a versatile accessory and one of the best gifts for mom, dad, students and professionals. Perfect for use as a laptop bed tray or tablet holder anywhere at home, library, or park.
window= raises an error in Pillow
Your installed Pillow may not expose that argument on the current platform or version. Inspect the installed reference, upgrade only after checking compatibility, or switch to the native Windows.Graphics.Capture route. Do not silently fall back to a crop if your requirement is window isolation.
Linux reports that a target is unsupported
The portal or backend may not advertise user-selected windows, or the interface version may predate that target. Query the portal capabilities, offer an area-selection fallback, and explain to the user that the fallback captures visible pixels.
The picker was cancelled
Treat cancellation as a normal outcome: return a distinct status, do not create a misleading empty file, and let the user reopen the picker.
Quick wins for a faster PC:
Clear out junk files and repair common Windows errorsFree Scan →Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →Repair Windows errors before they cause bigger problemsFix Now →Best Value
- Spacious Design: Measuring 21.1" wide and 12" deep, our lap desk comfortably fits most laptops up to 15.6". Extra room for accessories ensures convenience.
- Enhanced Functionality: Packed with handy features, including a 5x9" precision tracking mouse pad and a built-in phone slot for seamless work or video calls. Plus, enjoy laptop support with the integrated device ledge.
- Cool Comfort: Enjoy a stable surface with our lap desk's dual bolster cushion, designed for comfort and airflow, keeping your lap cool during extended use.
- Durable Surface: Work with confidence on our lap desk's solid surface, featuring a blush pink color, ensuring optimal air circulation to prevent your laptop from overheating.
- On-the-Go Convenience: With an integrated handle and lightweight design (2.14 lbs), our lap desk is portable for travel or moving around the house, offering flexibility in any space.
The wrong window was captured
Titles are not stable identifiers. Enumerate candidates with their process and visibility state, display a choice, and revalidate the native handle or window object immediately before requesting frames.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Reliability, performance and security considerations
- Permissions: OS capture consent can be revoked while the program runs; handle it as a recoverable error.
- Coordinate systems: Retina scaling, multiple monitors and negative coordinates make screen rectangles different from logical window bounds.
- Timing: wait until the target has rendered the state you need; a capture immediately after moving or resizing can be stale.
- Protected content: DRM or secure surfaces may intentionally refuse capture.
- Resource use: capture one frame when possible. Continuous native streams require explicit frame disposal and throttling; no performance figure should be assumed without testing your exact OS, compositor and application.
- Privacy: a screenshot can contain credentials and personal data. Restrict output permissions, avoid unnecessary retention and protect files sent to other services.
Or skip the browser setup
If your real goal is a screenshot of a web page rather than a native desktop window, ScreenshotNeo returns a PNG, JPEG, WebP or PDF from one HTTP request. It handles the browser session for you and offers an MCP server for Claude, Cursor and other MCP clients.
Python:
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
r.raise_for_status()
open("shot.webp", "wb").write(r.content)
See the ScreenshotNeo API documentation for options such as full-page capture, selectors, device presets, custom CSS and JavaScript, cookies, headers, waits, PDF settings, caching, bulk jobs and signed webhooks. Cookie banners, popups and chat widgets can be removed before capture; bot checks, blank pages and failed loads are not billed, and response headers identify the page verdict and billing result. The free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account.
Which approach should you ship?
Use a native, user-mediated API when you need a true application-window surface and can accept OS-specific integration. Use a portal on Linux when desktop-controlled selection is important. Use Pillow only after confirming the exact Windows/Pillow combination. Choose MSS or PyAutoGUI when a visible crop is explicitly acceptable. Document the platform, permission requirements, minimized-window behavior and cancellation path in your application rather than promising cross-platform equivalence.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
Frequently Asked Questions
Can Python capture a minimized window on every operating system?
No. The supplied interfaces differ by OS and compositor, and the documented material does not establish a universal minimized-window guarantee.
Is cropping a window’s coordinates the same as capturing the window?
No. A crop copies whatever pixels occupy that screen rectangle, including another window covering the target; a window-targeted API asks the operating system for the selected surface.
Do I need a Python package for Windows.Graphics.Capture or ScreenCaptureKit?
The cited guidance documents native Windows and macOS APIs, not turnkey Python recipes. You need a suitable binding, bridge or native helper.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.
Free tools Windows power users keep installed
One-click scans. No signup required.

