Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
pywin32 problems
#1
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:
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
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to find PyWin32 for Python 2.1.3 Paul_Newton 9 1,712 Nov-20-2022, 09:15 PM
Last Post: Paul_Newton
  pywin32: Outlook connection ends with 'operation aborted' on one machine tstone 0 2,403 May-03-2022, 04:29 AM
Last Post: tstone
  pywin32 Illustrator Throwing Exception Error matthewsjc1 7 5,610 Aug-27-2021, 02:43 AM
Last Post: Larz60+
  Has anyone figured out how to get pywin32 into a virtual environment yet? RobR 6 4,734 Jun-04-2020, 01:26 PM
Last Post: RobR
  wmi + pypiwin32 + pywin32 + Kodi NonSufficitOrbis 7 3,855 Aug-26-2019, 09:49 PM
Last Post: NonSufficitOrbis
  No module named pywin32 WantedStarling 3 12,267 Dec-07-2018, 09:11 PM
Last Post: Larz60+
  ISO working example of opening a Microsoft Word document through PyWin32 Orthoducks 1 4,617 Dec-25-2016, 10:12 PM
Last Post: snippsat

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020