3

I'm trying to get a full screenshots from an application window even when minimized, maximized, or any window shape. I've looked at other questions like this but havn't found the answer that I'm looking for.

I've tried the code below and it works, but has limited capability with what I want it to do.

def screenshot(hwnd = None):
    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)

    result = windll.user32.PrintWindow(hwnd, saveDC.GetSafeHdc(), 0)

    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:
    #PrintWindow Succeeded
    im.save(r"c:\python27\programs\check.bmp")

Using this code with a window that is maximized yields a great result!enter image description here

But when the window is shrinked.......not so much

enter image description here

I tried editing this line but end up with an akward result :/ . saveBitMap.CreateCompatibleBitmap(mfcDC, w+100, h+100)enter image description here

Does anyone know how to take a screenshot of a fully windowed application without maximizing then windowing again? Maybe something along the lines of using win32con.SW_MAXIMIZE.

Community
  • 1
  • 1
Alexander
  • 147
  • 1
  • 4
  • 11

1 Answers1

5

Why not use pywinauto + Pillow / PIL?

from pywinauto import application
app = application.Application().start("notepad.exe")
app.Untitled_Notepad.capture_as_image().save('window.png')
Vasily Ryabov
  • 9,386
  • 6
  • 25
  • 78
  • 3
    Thanks for responding! While pywinauto is FANTASTIC and able to do so much, that method is just a wrapper for Imagegrab from PIL which just takes a screen capture. Notepad would need to be the front foremost thing on the screen. I want to see if it's possible if it could be minimized or re-sized and still be able to capture all thats going on in the GUI. It's not that different from using `from PIL import ImageGrab ImageGrab.grab((100,100,200,200)).show()` Reference [CaptureAsImage](https://code.google.com/p/pywinauto/source/browse/pywinauto/controls/HwndWrapper.py?name=0.4.1) – Alexander Jun 18 '15 at 17:35