【发布时间】:2015-01-11 07:09:04
【问题描述】:
我有一个程序,它使用 pywin32 获取游戏的屏幕截图并使用 pygame 显示它。我遇到间歇性崩溃/挂起,程序会给出通常的窗口“不响应”错误,说 python.exe 有时在程序运行大约 5-10 秒后没有响应。
我已将其范围缩小到以下功能:
def screengrab(self):
hwnd = self.aoe_hwnd
left, top, right, bot = win32gui.GetClientRect(hwnd)
w = right - left
h = bot - top
#returns the device context (DC) for the entire window, including title bar, menus, and scroll bars.
hwndDC = win32gui.GetWindowDC(hwnd)
#Creates a DC object from an integer handle.
mfcDC = win32ui.CreateDCFromHandle(hwndDC)
#Creates a memory device context (DC) compatible with the specified device.
saveDC = mfcDC.CreateCompatibleDC()
saveDC.SetWindowOrg((w - self.map_w,h - self.map_h))
#Creates bitmap Object
saveBitMap = win32ui.CreateBitmap()
#Creates a bitmap object from a HBITMAP.
saveBitMap.CreateCompatibleBitmap(mfcDC, self.map_w, self.map_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(), 1)
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:
tmp = cStringIO.StringIO()
im = im.resize(self.window_size)
im.save(tmp, "bmp")
tmp.seek(0)
return tmp
我是 win32 的 api 的新手,我真的不完全确定是什么导致它这样挂起。奇怪的是,放置在程序主循环中的打印语句(也调用 screengrab())在程序挂起/无响应时仍会执行。
整个程序的要点:https://gist.github.com/Andygmb/f8ae761e689788136fc0
【问题讨论】:
标签: python winapi pywin32 win32gui