Python截图任意大小的应用程序窗口

时间:2015-06-15 13:31:34

标签: python python-2.7 pywin32

即使最小化,最大化或任何窗口形状,我也试图从应用程序窗口获取完整的屏幕截图。我看过其他问题,比如this但是找不到我正在寻找的答案。

我已经尝试了下面的代码并且它可以正常工作,但功能有限,我希望它能做到。

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")

将此代码与最大化的窗口一起使用会产生很好的结果!enter image description here

但是当窗户缩小时......不是那么多

enter image description here

我尝试编辑这一行,但结果却是一个不愉快的结果:/。 saveBitMap.CreateCompatibleBitmap(mfcDC, w+100, h+100) enter image description here

有没有人知道如何拍摄完全窗口化的应用程序的屏幕截图而不是最大化再次窗口化?也许就像使用win32con.SW_MAXIMIZE一样。

1 个答案:

答案 0 :(得分:5)

为什么不使用pywinauto + Pillow / PIL

from pywinauto import application
app = application.Application().start("notepad.exe")
app.Untitled_Notepad.capture_as_image().save('window.png')