python capturing offscreen picture result in blackscreen sometimes in middle of frame but edges showing?

Viewed 63

im working on windows trying to capture screen inside program like winamp video player(while it stayes in background and on top of it other programs running but not minimized state), and sometimes it capture it and sometimes in the middle it show black screen ,but rest of winamp edge is showing . i have tried redraw , sleep many things they all lead to 50 50 chances , sometimes it works sometimes no just black screen in the video place and edge of program showing , it happened with other graphic games sometimes it capture sometimes its black and corners showing ! the code im using :

import win32gui
import time
import win32ui
import win32con
from ctypes import windll
from PIL import Image
import os

hwnd = win32gui.FindWindow(None, os.sys.argv[1])



win32gui.ShowWindow(hwnd, win32con.SW_SHOWNORMAL)



# 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. 

time.sleep(0.080)
windll.user32.RedrawWindow(hwnd,  0, 0, win32con.RDW_FRAME or win32con.RDW_UPDATENOW )
win32gui.ShowWindow(hwnd, win32con.SW_RESTORE)

result = windll.user32.PrintWindow(hwnd, saveDC.GetSafeHdc(), 0)
time.sleep(0.1)
print(result)


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

#win32gui.ShowWindow(hwnd, win32con.SW_SHOWMINIMIZED)

win32gui.ShowWindow(hwnd, win32con.SW_SHOWNOACTIVATE)

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")
0 Answers
Related