Python 3: Script exits with exit code -1073740771 (0xC000041D), while trying to get a screenshot of window using PyWin32

1

My script, using Tkinter to create a window, gets a bitmap image with PyWin32, convert the bitmap into a Pillow Image. Then save it to test.png.

The code:

import os
from tkinter import Tk, Frame, Button

import win32gui
import win32ui
from ctypes import windll
from PIL import Image

root = Tk()

frame = Frame(root, bg="#ff0000")
button = Button(frame, bg="#7c7c7c")
button.pack(pady=10, padx=10)
frame.pack(fill="both", expand=True)

root.update()

hwnd = win32gui.GetParent(root.winfo_id())

# Change the line below depending on whether you want the whole window
# or just the client area.
left, top, right, bot = win32gui.GetClientRect(hwnd)
# left, top, right, bot = win32gui.GetWindowRect(hwnd)
w = right - left
h = bot - top

hwndDC = win32gui.GetWindowDC(hwnd)
mfcDC = win32ui.CreateDCFromHandle(hwndDC)
saveDC = mfcDC.CreateCompatibleDC()

saveBitMap = win32ui.CreateBitmap()
saveBitMap.CreateCompatibleBitmap(mfcDC, w, h)

saveDC.SelectObject(saveBitMap)

# Change the line below depending on whether you want the whole window
# or just the client area.
result = windll.user32.PrintWindow(hwnd, saveDC.GetSafeHdc(), 1)
# result = windll.user32.PrintWindow(hwnd, saveDC.GetSafeHdc(), 0)
print(result)

bmpinfo = saveBitMap.GetInfo()
bmpstr = saveBitMap.GetBitmapBits(True)

im = Image.frombuffer(
    'RGB',
    (bmpinfo['bmWidth'], bmpinfo['bmHeight']),
    bmpstr, 'raw', 'BGRX', 0, 1)

win32gui.DeleteObject(saveBitMap.GetHandle())
saveDC.DeleteDC()
mfcDC.DeleteDC()
win32gui.ReleaseDC(hwnd, hwndDC)

if result == 1:
    #PrintWindow Succeeded
    im.save("test.png")

# root.wm_protocol("WM_DELETE_WINDOW", lambda: os.kill(os.getpid(), 0))

root.mainloop()

Also my idea is to have to get an image of the window, even another window overlaps it.
Even when the window is minimized.

This is the PyCharm output:

1

Process finished with exit code -1073740771 (0xC000041D)

It crashes when closing the window.
Does anyone know what's going wrong?
By the way, it seems it's happening with this bit of code: root.update(). @interflexo said that import win32ui is doing it. I think there's a conflict with these two.

python-3.x
tkinter
python-imaging-library
pywin32
asked on Stack Overflow May 12, 2020 by Qboi123 • edited Apr 21, 2021 by Qboi123

1 Answer

0

Just adding this import at top of my code

import win32ui

triggers this behavior.

answered on Stack Overflow Mar 31, 2021 by interflexo • edited Apr 1, 2021 by Damian-Teodor BeleČ™

User contributions licensed under CC BY-SA 3.0