Skip to content

Instantly share code, notes, and snippets.

@Andygmb
Created January 10, 2015 04:35
Show Gist options
  • Save Andygmb/ca759eb42792a145efd0 to your computer and use it in GitHub Desktop.
Save Andygmb/ca759eb42792a145efd0 to your computer and use it in GitHub Desktop.
def screengrab(self):
# Change the line below depending on whether you want the whole window
# or just the client area.
#left, top, right, bot = win32gui.GetClientRect(hwnd)
hwnd = self.aoe_window
left, top, right, bot = win32gui.GetClientRect(hwnd)
w = right - left
h = bot - top
#returns the device context (DC) for the entire window, including title bar, menus, and scroll bars.
hwndDC = win32gui.GetWindowDC(hwnd)
#Creates a DC object from an integer handle.
mfcDC = win32ui.CreateDCFromHandle(hwndDC)
#Creates a memory device context (DC) compatible with the specified device.
saveDC = mfcDC.CreateCompatibleDC()
saveDC.SetWindowOrg((w - self.map_w,h - self.map_h))
#Creates bitmap Object
saveBitMap = win32ui.CreateBitmap()
#Creates a bitmap object from a HBITMAP.
saveBitMap.CreateCompatibleBitmap(mfcDC, self.map_w, self.map_h)
saveDC.SelectObject(saveBitMap)
# Change the line below depending on whether you want the whole window
# or just the client area.
#result = windll.user32.PrintWindow(hwnd, saveDC.GetSafeHdc(), 1)
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:
tmp = cStringIO.StringIO()
im = im.resize(self.window_size)
im.save(tmp, "bmp")
tmp.seek(0)
return tmp
# # Create cStringIO file object
# tmp = cStringIO.StringIO()
# # Grab image, save to temp file object
# screengrab = ImageGrab.grab(bbox=self.map_bbox).resize(self.window_size)
# screengrab.save(tmp, "bmp")
# # Seeking tells the file object to start at byte 0
# tmp.seek(0)
# return tmp
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment