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

Ale*_*der 3 python pywin32 python-2.7

即使在最小化,最大化或任何窗口形状的情况下,我也试图从应用程序窗口获取完整的屏幕截图.我看像其他问题,却没有带发现我要找的答案.

我已经尝试了下面的代码并且它可以工作,但功能有限,我想要它做什么.

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")
Run Code Online (Sandbox Code Playgroud)

将此代码与最大化的窗口一起使用会产生很好的效果!在此输入图像描述

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

在此输入图像描述

我尝试编辑这一行,但结果却是一个不愉快的结果:/. saveBitMap.CreateCompatibleBitmap(mfcDC, w+100, h+100)在此输入图像描述

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

Vas*_*bov 5

为什么不使用pywinauto + Pillow/PIL

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

  • 谢谢你的回复!虽然pywinauto非常棒并且能够做到这么多,但是这种方法只是PIL的Imagegrab的一个包装器,只需要一个屏幕截图.记事本需要成为屏幕上最前面的东西.我想看看它是否可能被最小化或重新调整大小,并且仍然能够捕获GUI中正在发生的所有事情.与使用`来自PIL导入ImageGrab ImageGrab.grab((100,100,200,200))没有什么不同.show()`参考[CaptureAsImage](https://code.google.com/p/pywinauto/source/browse/pywinauto/controls /HwndWrapper.py?name=0.4.1) (3认同)