Apr-01-2022, 01:04 PM
I was trying to take a screenshot of a hidden window so I found the code below. But there are so many new terms I don't understand.
Can anyone explain what the device context is? Is it like an address of an image in a monitor device or printer?
if so why I can't directly get the content from the address(DC) and save as a var of bitmap and convert it to png and save it?
Instead, they did it like this:
Can anyone explain what the device context is? Is it like an address of an image in a monitor device or printer?
if so why I can't directly get the content from the address(DC) and save as a var of bitmap and convert it to png and save it?
Instead, they did it like this:
import win32gui import win32ui from ctypes import windll from PIL import Image hwnd = win32gui.FindWindow(None, 'Calculator') left, top, right, bot = win32gui.GetWindowRect(hwnd) w = right - left h = bot - top hwndDC = win32gui.GetWindowDC(hwnd) #^^^HERE^^^ now I've got the DC handle (hwndDC) can't I just extract image content from it? mfcDC = win32ui.CreateDCFromHandle(hwndDC) #^^^HERE^^^ why create a new DC? what's the relationship of this new DC with the DC obj from hwndDC saveDC = mfcDC.CreateCompatibleDC() #^^^HERE^^^ this has the same type as mfcDC but this seems to be called a memory device context, what for? saveBitMap = win32ui.CreateBitmap() saveBitMap.CreateCompatibleBitmap(mfcDC, w, h) #^^^HERE^^^Shouldn't it create bitmap from the DC obj of hwndDC instead of mfcDC saveDC.SelectObject(saveBitMap) result = windll.user32.PrintWindow(hwnd, saveDC.GetSafeHdc(), 2) #^^^HERE^^^ What is this for? bmpinfo = saveBitMap.GetInfo() bmpstr = saveBitMap.GetBitmapBits(True) im = Image.frombuffer( 'RGB', (bmpinfo['bmWidth'], bmpinfo['bmHeight']), bmpstr, 'raw', 'BGRX', 0, 1) im.save('img.png') win32gui.DeleteObject(saveBitMap.GetHandle()) saveDC.DeleteDC() mfcDC.DeleteDC() win32gui.ReleaseDC(hwnd, hwndDC)Sorry about so many question but I'm really confused