This code worked for me with applications in background, not minimized.

import win32gui
import win32ui

def background_screenshot(hwnd, width, height):
    wDC = win32gui.GetWindowDC(hwnd)
    dcObj=win32ui.CreateDCFromHandle(wDC)
    cDC=dcObj.CreateCompatibleDC()
    dataBitMap = win32ui.CreateBitmap()
    dataBitMap.CreateCompatibleBitmap(dcObj, width, height)
    cDC.SelectObject(dataBitMap)
    cDC.BitBlt((0,0),(width, height) , dcObj, (0,0), win32con.SRCCOPY)
    dataBitMap.SaveBitmapFile(cDC, 'screenshot.bmp')
    dcObj.DeleteDC()
    cDC.DeleteDC()
    win32gui.ReleaseDC(hwnd, wDC)
    win32gui.DeleteObject(dataBitMap.GetHandle())

hwnd = win32gui.FindWindow(None, windowname)
background_screenshot(hwnd, 1280, 780)
Answer from Alexandre Calil on Stack Overflow
🌐
Reddit
reddit.com › r/learnpython › creating screenshot of a certain window (without changing to foreground)
r/learnpython on Reddit: Creating screenshot of a certain window (without changing to foreground)
January 3, 2023 -

I am performing image search on a certain window, that I am trying to automate.

At the same time, I show debug information in a borderless window on top of the screen.

This window interferes with the image search that I am trying to do.

The solution would be to not create a screenshot of the whole screen, but a certain window.

Solutions I have found on the internet require moving certain windows to the top, but this wouldn't work as the debug window is always on top. I know it is possible, because programs like OBS can only grab a certain window.

Simplified code (because required):

import python_imagesearch.imagesearch as imgsearch

searchResult = imgsearch.imagesearch("./imagery/shop.png",0.9)

🌐
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?

🌐
Toolify
toolify.ai › ai-news › capture-any-window-using-python-tutorial-174997
Capture any window using Python [Tutorial]
December 27, 2023 - Learn how to take screenshots of specific windows on Windows and macOS with this Python tutorial.
🌐
GitHub
github.com › pywinauto › pywinauto › issues › 995
Capture image of window even if in background? · Issue #995 · pywinauto/pywinauto
October 19, 2020 - Sort of like the code here -- https://github.com/marcosboggia/gui_automation/blob/master/gui_automation/background_handler.py · If not, is there a way to get the handler/hwnd from a UIA app and then call code myself to do this? capture_as_image() would work even if the window is obscured by another window
Author   lex3001
🌐
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
🌐
TutorialsPoint
tutorialspoint.com › how-to-take-a-screenshot-of-the-window-using-python-tkinter
How to take a screenshot of the window using Python?(Tkinter)
June 18, 2021 - # Import the required libraries from tkinter import * import time from PIL import ImageTk, Image import pyautogui as pg # Create an instance of tkinter frame or window win = Tk() # Set the size of the window win.geometry("700x350") # Define a function for taking screenshot def screenshot(): random = int(time.time()) filename = "C:/Users/Sairam/Documents/" \ + str(random) + ".jpg" ss = pg.screenshot(filename) ss.show() win.deiconify() def hide_window(): # hiding the tkinter window while taking the screenshot win.withdraw() win.after(1000, screenshot) # Add a Label widget Label(win, text="Click the Button to Take the Screenshot", font=('Times New Roman', 18, 'bold')).pack(pady=10) # Create a Button to take the screenshots button = Button(win, text="Take Screenshot", font=('Aerial 11 bold'), background="#aa7bb1", foreground="white", command=hide_window) button.pack(pady=20) win.mainloop()
Find elsewhere
🌐
Quora
quora.com › What-Python-script-makes-a-snapshot-of-application-window-on-Windows-OS
What Python script makes a snapshot of application window on Windows OS? - Quora
Answer: You can do it with something like this [code]import win32gui import win32ui import win32con from time import sleep def _get_windows_bytitle(title_text, exact = False): def _window_callback(hwnd, all_windows): all_windows.append((hwnd, win32gui.GetWindowText(hwnd))) wind...
🌐
Finxter
blog.finxter.com › how-to-get-a-windows-screenshot-in-python
How to Get a Windows Screenshot in Python? – Be on the Right Side of Change
August 10, 2021 - Say, you run a Python program on your Windows machine and you want it to take a screenshot. How to accomplish this programmatically? To programmatically record one or more screenshots in your Python program, run the sct.shot() function from the mss module. ♥️ Info: Are you AI curious but you still have to create real impactful projects? Join our official ...
🌐
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 › codinggpt
python get screenshot of specific window - YouTube
Download this code from https://codegive.com Certainly! Capturing a screenshot of a specific window in Python involves using libraries such as pyautogui or P...
Published   December 23, 2023
Views   251
🌐
ResearchGate
researchgate.net › figure › Screenshot-of-the-developed-python-script-The-screen-on-the-background-left-records_fig2_356168455
Screenshot of the developed python script. The screen on the background... | Download Scientific Diagram
Download scientific diagram | Screenshot of the developed python script. The screen on the background (left) records the keystrokes. The screen on the foreground (right) shows the information of the current window and a legend with the correspondences between keys and labels. from publication: ...
Top answer
1 of 2
6

It's probably the fault of the game, not the fault of the screenshot utility. X11 sends applications a VisibilityNotify event to tell them that their window is fully visible, partially obscured or totally obscured. When the window is totally obscured, most applications don't bother updating their display, which saves resources. In other words, if nobody is there to see it, the tree doesn't fall.

I think that if you send the game window a VisibilityNotify event to pretend that it's visible, then you'll get your screenshot. You'll need to send the event after the window becomes obscured, since X11 itself will send its normal event at that time. Here's an untested script that sends a VisibilityNotify event, call it with the argument VisibilityPartiallyObscured or VisibilityUnobscured. I follow with a MapNotify event, I don't know if it's useful. You need Python and Python-xlib.

#! /usr/bin/env python
import re, sys, time
import Xlib.X, Xlib.XK, Xlib.display, Xlib.protocol

def parse_action(string):
    state = {
              '0': 0,
              '1': 1,
              '2': 2,
              'unobscured': 0,
              'partiallyobscured': 1,
              'fullyobscured': 2,
              'visibilityunobscured': 0,
              'visibilitypartiallyobscured': 1,
              'visibilityfullyobscured': 2,
             }[string.lower()]
    return state

def parse_window(display, arg):
    wid = int(arg, 0)
    return display.create_resource_object('window', wid)

def send_event(display, window, state):
    window.send_event(Xlib.protocol.event.VisibilityNotify(window=window,
                                                           state=state))
    window.send_event(Xlib.protocol.event.MapNotify(window=window,
                                                    event=window,
                                                    override=False))
    display.sync()

if __name__ == "__main__":
    display = Xlib.display.Display()
    send_event(display, parse_window(display, sys.argv[1]), parse_action(sys.argv[2]))
2 of 2
3

If you don't have xwd and xwud already installed on your system I would be very surprised if you could not easily install them via package manager in a few seconds at most.

% man xwd

NAME
       xwd - dump an image of an X window

SYNOPSIS
       xwd  [-debug] [-help] [-nobdrs] [-out file] [-xy] [-frame] [-add value]
       [-root | -id id | -name name ] [-icmap] [-screen]  [-silent]  [-display
       display]

DESCRIPTION
       Xwd  is  an X Window System window dumping utility.  Xwd allows X users
       to store window images in a specially formatted dump file.   This  file
       can  then be read by various other X utilities for redisplay, printing,
       editing, formatting, archiving, image processing, etc.  The target win‐
       dow  is  selected  by  clicking the pointer in the desired window.  The
       keyboard bell is rung once at the beginning of the dump and twice  when
       the dump is completed.

Understand this is a sort of a desktop session recording software - built into the X-server - it does enable you take screenshots, and much more. But you'll want to read the documentation a little before diving in - just to get familiar with it, I think.

Note - the target window does not need to be selected via mouse-cursor as mentioned above - that's just the default behavior when it's invoked without arguments. The entire interface is completely scriptable.

Just scroll a little more and...

   -root   This option indicates that the root window should  be  selected
           for  the  window  dump,  without requiring the user to select a
           window with the pointer.

   -id id  This option  indicates  that  the  window  with  the  specified
           resource  id  should  be  selected for the window dump, without
           requiring the user to select a window with the pointer.

If you'll take my advice you'll also look pretty closely at xdotool, though, admittedly it has limited relevance here. It scripts the mouse mostly, though it does offer some direct command-line interface to the X backend api - as @Gilles references. And it's pretty simple to use.

All that said, the primary issue is that your display is currently occupied. If your window must remain invisible it is possible to handle it in a few ways - though you'll have to try at them a little, I think, before you get them down. The way I would recommend is merely to configure your screen to be twice the size of your screen. That way you can just drag the window off of the screen and it will continue to update the display - but off screen. I can do this with nvidia's tools, and most can do this with xrandr, but, especially in Linux it seems, at least in my experience, display issues are often personal issues just because there are so many possible ways to configure them.

Another way this might be done is with a virtual X-server - such as xnest or xephyr. These servers nest an entire X-server within a window which can be backgrounded, or completely nonexistent if you prefer. Last I checked, which was some time ago unfortunately, these were using the xdummy-driver - and would therefore not be good choices for a video game that required video acceleration. Still, I'm sure your man pages could tell you more, and I can only hope I helped.

🌐
PyPI
pypi.org › project › fast-ctypes-screenshots
fast-ctypes-screenshots · PyPI
from time import time import cv2 import numpy as np from fast_ctypes_screenshots import ( ScreenshotOfRegion, ScreenshotOfOneMonitor, ScreenshotOfAllMonitors, ScreenshotOfWindow, ) # a simple benchmark function def show_screenshot( screenshotiter, stop_at_frame=100, quitkey="q", show_screenshot=True ): def show_screenshotx(): cv2.imshow("test", screenshot) if cv2.waitKey(1) & 0xFF == ord(quitkey): cv2.destroyAllWindows() return False return True framecounter = 0 fps = 0 start_time = time() for screenshot in screenshotiter: if stop_at_frame: if framecounter > stop_at_frame: break framecounter +
      » pip install fast-ctypes-screenshots
    
Published   May 19, 2023
Version   0.10
🌐
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 - Line 29 to 46, we create a function for taking the actual screenshots while using the window information (The size and the location) — and line 41 is very important because the window can be resized and moved around, so without it… we’re doomed! That is to say the screenshot taken would be the area the window was created first.
🌐
Medium
medium.com › @rahbarysina › 1-practical-python-how-to-take-screenshot-using-python-605469329025
1) Practical python, How to take Screenshot using Python | by Sina | Medium
September 14, 2023 - Now, let’s write a Python script to take a screenshot. We’ll capture the entire screen, but you can modify the code to capture specific regions or windows if needed.
🌐
Quora
quora.com › How-can-we-take-screenshots-using-Python-in-Windows
How can we take screenshots using Python in Windows? - Quora
Answer (1 of 3): This tutorial will help you to hack windows , Lets start the tutorial. Taking Screenshots Most pieces of malware and penetration testing frameworks include the capability to take screen shots against the remote target. This can help capture images, video frames, or other sensit...
🌐
PyPI
pypi.org › project › windows-adb-screen-capture
windows-adb-screen-capture · PyPI
sc2 = ScreenShots() sc2.find_window_with_regex('[bB]lue[sS]tacks.*') sc2.imshow_hwnd(sleep_time=0.05, quit_key="q") #show captured screen
      » pip install windows-adb-screen-capture
    
Published   Nov 24, 2022
Version   0.17