Python screenshot 2+ monitors (windows)

2020-07-06 06:32发布

问题:

How to make a screenshot with python, if connected to multiple monitors?

I tried:

import sys
from PyQt4.QtGui import QPixmap, QApplication
app = QApplication(sys.argv)
QPixmap.grabWindow(QApplication.desktop().winId()).save('test.png', 'png')

import ImageGrab
im = ImageGrab.grab()
im.save('test.png', 'PNG')

Both options provide a screenshot, only the primary monitor

If I use winapi:

hWnd = win32gui.FindWindow(None, win_name)
dc = win32gui.GetWindowDC(hWnd)
i_colour = int(win32gui.GetPixel(dc,int(x),int(y)))
rgb = ((i_colour & 0xff), ((i_colour >> 8) & 0xff), ((i_colour >> 16) & 0xff))

I get a picture from a window in the second monitor. But it will be very slow.

If I press key 'printscreen' in the clipboard will be a normal screenshot, with all monitors. Is there a option to get a Full screenshot in Python?

回答1:

Using a mix of wxPython, win32api and ctypes:

import wx, win32api, win32gui, win32con, ctypes

class App(wx.App):
    def OnInit(self):
        dll = ctypes.WinDLL('gdi32.dll')
        for idx, (hMon, hDC, (left, top, right, bottom)) in enumerate(win32api.EnumDisplayMonitors(None, None)):
            hDeskDC = win32gui.CreateDC(win32api.GetMonitorInfo(hMon)['Device'], None, None)
            bitmap = wx.EmptyBitmap(right - left, bottom - top)
            hMemDC = wx.MemoryDC()
            hMemDC.SelectObject(bitmap)
            try:
                dll.BitBlt(hMemDC.GetHDC(), 0, 0, right - left, bottom - top, int(hDeskDC), 0, 0, win32con.SRCCOPY)
            finally:
                hMemDC.SelectObject(wx.NullBitmap)
            bitmap.SaveFile('screenshot_%02d.bmp' % idx, wx.BITMAP_TYPE_BMP)
            win32gui.ReleaseDC(win32gui.GetDesktopWindow(), hDeskDC)
        return False

App(0)


回答2:

My Desktopmagic library provides this functionality for Python 2.6, 2.7, and 3.3+. It can return a PIL/Pillow Image or write a BMP.