Reputation: 11
I'm trying to capture a window by its HWND, like my explorer:
But this is the result I get:
This is the function I am using:
def capture_window(hwnd):
win32gui.ShowWindow(hwnd, win32con.SW_RESTORE)
win32gui.SetForegroundWindow(hwnd)
time.sleep(1)
window_dc = win32gui.GetWindowDC(hwnd)
dc_object = win32ui.CreateDCFromHandle(window_dc)
compatible_dc = dc_object.CreateCompatibleDC()
left, top, right, bottom = win32gui.GetClientRect(hwnd)
width = right - left
height = bottom - top
bitmap = win32ui.CreateBitmap()
bitmap.CreateCompatibleBitmap(dc_object, width, height)
compatible_dc.SelectObject(bitmap)
compatible_dc.BitBlt((0, 0), (width, height), dc_object, (0, 0), win32con.SRCCOPY)
bmpinfo = bitmap.GetInfo()
bmpstr = bitmap.GetBitmapBits(True)
img = Image.frombuffer(
"RGB", (bmpinfo["bmWidth"], bmpinfo["bmHeight"]), bmpstr, "raw", "BGRX", 0, 1
)
img = cv2.cvtColor(np.array(img), cv2.COLOR_BGR2RGB)
win32gui.DeleteObject(bitmap.GetHandle())
compatible_dc.DeleteDC()
dc_object.DeleteDC()
win32gui.ReleaseDC(hwnd, window_dc)
return img
The title bar is black, and there is some shift in its position.
Some windows seem alright, but some are not (like explorer). What is causing this?
I tried to fix it with changing win32gui.GetClientRect()
to win32gui.GetWindowRect()
, but it didn't work. I am expecting it can capture a same image.
Upvotes: 1
Views: 59