Created
November 14, 2018 17:06
-
-
Save june9713/784898001255ec97f4f488432ff4a880 to your computer and use it in GitHub Desktop.
take screenshot from background window partitially
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import win32gui | |
import win32ui | |
import win32con | |
from PIL import Image | |
import time | |
import ctypes | |
import traceback | |
''' | |
you can fastly capture with printwindow by | |
removimg unuse region from windows. | |
''' | |
def get_windows(): | |
'''Returns windows in z-order (top first)''' | |
user32 = ctypes.windll.user32 | |
lst = [] | |
top = user32.GetTopWindow(None) | |
if not top: | |
return lst | |
lst.append(top) | |
while True: | |
next = user32.GetWindow(lst[-1], win32con.GW_HWNDNEXT) | |
if not next: | |
break | |
lst.append(next) | |
return lst | |
tb = time.time() | |
for hwnd in get_windows(): | |
if win32gui.IsWindowVisible(hwnd): | |
try: | |
left, top, right, bot = win32gui.GetClientRect(hwnd) | |
#left, top, right, bot = win32gui.GetWindowRect(hwnd) | |
w = right - left | |
h = bot - top | |
hwndDC = win32gui.GetWindowDC(hwnd) | |
mfcDC = win32ui.CreateDCFromHandle(hwndDC) | |
saveDC = mfcDC.CreateCompatibleDC() | |
saveBitMap = win32ui.CreateBitmap() | |
saveBitMap.CreateCompatibleBitmap(mfcDC, w, h) | |
saveDC.SelectObject(saveBitMap) | |
# you can change w ,h , left , top for geometry you want | |
result = saveDC.BitBlt((0, 0), (w, h), mfcDC, (left, top), win32con.SRCCOPY) | |
bmpinfo = saveBitMap.GetInfo() | |
bmpstr = saveBitMap.GetBitmapBits(True) | |
try: | |
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) | |
im.save("./%s.png"%(hwnd)) | |
except: | |
pass | |
except: | |
print(traceback.format_exc()) | |
print(time.time()-tb) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment