This code takes a screenshot of the entire program. I want to take screenshots of only a small part of the program.
Even if i change w(wide) and h(height) in the code below screenshot is taken starting from the top left corner of the program.
For example, this code can range from 0,0 (top left) to the desired x,y. But what I want is to take a screenshot from x1,y1 to x2,y2. What do I need to add or modify?
(I used google translator. I've tried to explain it as best as I can.) thank you
from tkinter import *
import win32gui
import win32ui
from PIL import Image
from ctypes import windll
def screenshot():
hwnd = win32gui.FindWindow(None, 'program_name') #input program name
#left, top, right, bot = win32gui.GetClientRect(hwnd)
left, top, right, bot = win32gui.GetWindowRect(hwnd)
w = right - left #wide
h = bot - top #hight
hwndDC = win32gui.GetWindowDC(hwnd)
mfcDC = win32ui.CreateDCFromHandle(hwndDC)
saveDC = mfcDC.CreateCompatibleDC()
saveBitMap = win32ui.CreateBitmap()
saveBitMap.CreateCompatibleBitmap(mfcDC, w, h)
saveDC.SelectObject(saveBitMap)
#result = windll.user32.PrintWindow(hwnd, saveDC.GetSafeHdc(), 0)
result = windll.user32.PrintWindow(hwnd, saveDC.GetSafeHdc(), 1)
bmpinfo = saveBitMap.GetInfo()
bmpstr = saveBitMap.GetBitmapBits(True)
im = Image.frombuffer(
'RGB',
(bmpinfo['bmWidth'], bmpinfo['bmHeight']),
bmpstr, 'raw', 'BGRX', 0, 1)
win32gui.DeleteObject(saveBitMap.GetHandle())
saveDC.DeleteDC()
mfcDC.DeleteDC()
win32gui.ReleaseDC(hwnd, hwndDC)
if result == 1: #if Succeeded
im.save("C:/Users/Moon/Desktop/test.png") #save path need change
else:
print("Error")
screenshot()