Search code examples
pythonwinapirenderingscreenshotbitblt

Can I take a screenshot on a windows machine that is running without a monitor?


I have a bank of virtual machines (running windows) that I remote into. As such, none of these machines have a monitor attached, they are only accessed by Remote Desktop.

I want to get a screenshot of an application that is running on the desktop. What I have found is that if I am not connected via Remote Desktop, then the screen is not rendering and I am unable capture the screen (the best I've managed is getting a black image).

Is there any way to force the desktop to render for the purpose of my screen grab?

EDIT: OK to be more specific, here is some Python code that takes a screenshot provided I am remoted in to the machines:

import win32ui
import win32gui
hwnd = win32gui.FindWindow(None, window_name)
wDC = win32gui.GetWindowDC(hwnd)
dcObj = win32ui.CreateDCFromHandle(wDC)
cDC=dcObj.CreateCompatibleDC()
dataBitMap = win32ui.CreateBitmap()
dataBitMap.CreateCompatibleBitmap(dcObj, width, height)
cDC.SelectObject(dataBitMap)
cDC.BitBlt((0, 0), (width, height), dcObj, (0, 0), win32con.SRCCOPY)
dataBitMap.SaveBitmapFile(cDC, image_name)
# Free Resources
dcObj.DeleteDC()
cDC.DeleteDC()
win32gui.ReleaseDC(hwnd, wDC)
win32gui.DeleteObject(dataBitMap.GetHandle())

If I run this while I am remoted in, it works fine. As soon as I am not remoted in, I get the following error:

win32ui.error: BitBlt failed

This error is a result of the screen not being rendered when no one is remoted in.

I need a solution that will allow me to get a screenshot in this scenario, when I am not connected via remote desktop.

EDIT 2: To be clear, the code is running on the VM itself. But it is running when no-one is remoted in to the machine.


Solution

  • Obvious workaround is using 2 virtual machines: master host runs remote session for target one. It also allows input actions like mouse_event or keybd_event. The only one requirement is not to minimize RDP window (or VNC software, it's doesn't matter), though it may be out of focus.

    It's widely used method for build/test machines pool. I worked in big testing team several years and never heard about other approaches.

    P.S. How about Pillow or pyscreenshot?