- 1 year ago
Screenshot of the specific window (HWND, HW accelerated)
To capture a screenshot of a specific window identified by its HWND (window handle) in Python, you can use the pygetwindow
library along with the PIL
(Python Imaging Library) or Pillow
library for image processing. Here's an example:
First, install the required libraries:
shellpip install pygetwindow
pip install Pillow
Then, you can use the following code to capture a screenshot of a specific window:
pythonimport pygetwindow as gw
from PIL import ImageGrab
# Get the window by its HWND
window = gw.win32wrapper.GetWindowFromHandle(hwnd) # Replace hwnd with the actual window handle
# Get the window coordinates
left, top, right, bottom = window.left, window.top, window.right, window.bottom
# Capture the screenshot
screenshot = ImageGrab.grab(bbox=(left, top, right, bottom))
# Save the screenshot to a file
screenshot.save('window_screenshot.png')
In this example, we use pygetwindow
to get a reference to the window using its HWND (hwnd
), and then we retrieve the window's coordinates (left
, top
, right
, bottom
). We then use PIL
or Pillow
to capture a screenshot of the specified region using ImageGrab.grab()
with the provided bounding box. Finally, we save the captured screenshot to a file (window_screenshot.png
in this case).
Make sure to replace hwnd
with the actual HWND of the target window for which you want to capture a screenshot.
Please note that capturing screenshots of windows that are running in hardware-accelerated mode (e.g., games, GPU-accelerated applications) might not be directly supported by this method, as the window contents might not be accessible by conventional screenshot capture techniques. In such cases, specialized libraries or tools specific to the application or game may be required to capture accurate screenshots.