Skip to content

Instantly share code, notes, and snippets.

@SmartManoj
Last active November 8, 2022 04:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SmartManoj/245130d9558c700cb6d7f65b8b81df1d to your computer and use it in GitHub Desktop.
Save SmartManoj/245130d9558c700cb6d7f65b8b81df1d to your computer and use it in GitHub Desktop.
import io
import pyautogui
from time import sleep
import win32clipboard
from PIL import ImageGrab
import win32gui
toplist, winlist = [], []
def enum_cb(hwnd, results):
winlist.append((hwnd, win32gui.GetWindowText(hwnd)))
win32gui.EnumWindows(enum_cb, toplist)
handles = [(hwnd, title)
for hwnd, title in winlist if 'nokia' in title.lower()]
# just grab the hwnd for first window matching firefox
hwnd = handles[0]
win32gui.SetForegroundWindow(hwnd)
bbox = win32gui.GetWindowRect(hwnd)
# add 10px to the left and top, and subtract 10px from the right and bottom
bbox = (bbox[0] + 10, bbox[1] + 40, bbox[2] - 10, bbox[3] - 10)
# move cursor using pyautogui
# pyautogui.moveTo(bbox[0]+5, bbox[1]+5)
# without above line, sometimes it captures different region in Windows 11.
sleep(1)
img = ImageGrab.grab(bbox)
# img.show()
# copy image to clipboard
# img.save('nokia.png')
win32clipboard.OpenClipboard()
win32clipboard.EmptyClipboard()
with io.BytesIO() as output:
img.convert("RGB").save(output, "BMP")
data = output.getvalue()[14:]
win32clipboard.SetClipboardData(win32clipboard.CF_DIB, data)
win32clipboard.CloseClipboard()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment