0

I have a python script that uses win32ui.CreateBitmap() to take screenshots. It works fine but when my monitor is turned off, it stops working. Is there a way to get the screenshot working while monitor is turned off?

My screengrab code is below:

def screengrab(self):
        # Screen grab via Windows API
        # https://stackoverflow.com/a/3586280

        wDC = win32gui.GetWindowDC(self.bs.hwnd)
        dcObj = win32ui.CreateDCFromHandle(wDC)
        cDC = dcObj.CreateCompatibleDC()

        x1, y1, x2, y2 = win32gui.GetWindowRect(self.bs.hwnd)
        w = x2 - x1
        h = y2 - y1
        try:
            dataBitMap = win32ui.CreateBitmap()
            dataBitMap.CreateCompatibleBitmap(dcObj, w, h)
            cDC.SelectObject(dataBitMap)
            cDC.BitBlt((0,0),(w, h) , dcObj, (0,0), win32con.SRCCOPY)
            
            im = np.frombuffer(dataBitMap.GetBitmapBits(True), 
                               dtype=np.uint8)
            bmInfo = dataBitMap.GetInfo()
            im = im.reshape(bmInfo['bmHeight'], 
                            bmInfo['bmWidth'], 4)[:, :, -2::-1]
        except Exception as e:
            dcObj.DeleteDC()
            cDC.DeleteDC()
            win32gui.ReleaseDC(self.bs.hwnd, wDC)
            win32gui.DeleteObject(dataBitMap.GetHandle())
            raise Exception(e)
        
        # Free resources
        dcObj.DeleteDC()
        cDC.DeleteDC()
        win32gui.ReleaseDC(self.bs.hwnd, wDC)
        win32gui.DeleteObject(dataBitMap.GetHandle())

        return im
tfu
  • 53
  • 2
  • 5
  • Define "stops working". – Jabberwocky Aug 26 '20 at 12:08
  • @Jabberwocky It wasn't able to take screengrabs and code just stalls. I figured it out though and it's not code related. I was using a displayport, swapped it with HDMI and it started working. Maybe it has something to do with DP disconnecting the monitor when it is turned off. – tfu Aug 26 '20 at 15:01
  • You shpould find out _where exactly_ the code stalls. – Jabberwocky Aug 26 '20 at 15:03
  • I tested the code to work normally after turning off the monitor. Do you have any further reasons for the error? – Zeus Aug 27 '20 at 03:16

0 Answers0