未激活窗口的屏幕截图 PrintWindow + win32gui

21

经过数小时的谷歌搜索,我设法“编写”了以下代码:

import win32gui
from ctypes import windll

hwnd = win32gui.FindWindow(None, 'Steam')

hdc = win32gui.GetDC(hwnd)
hdcMem = win32gui.CreateCompatibleDC(hdc)
    
hbitmap = win32ui.CreateBitmap()
hbitmap = win32gui.CreateCompatibleBitmap(hdcMem, 500, 500)
    
win32gui.SelectObject(hdcMem, hbitmap)
    
windll.user32.PrintWindow(hwnd, hdcMem, 0)

这样做的方式是否正确,如何保存图像?

1个回答

67

经过大量搜索和尝试不同的方法,以下方法对我有效。

import win32gui
import win32ui
from ctypes import windll
import Image

hwnd = win32gui.FindWindow(None, 'Calculator')

# 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")

4
好的回答!我浪费了最近两个小时试图将完全相同的 C++ 代码转换为 Python,只发现您已经完成了这项工作。请问您是否介意更详细地解释每一行代码正在做什么? - d34th4ck3r
4
对我没有用。我正在使用Python 3.7x,并做了一些适应性调整,但最终得到的只是一些空白的黑色屏幕截图,而不是计算器应该有的样子。有什么帮助吗? - Mitrek
3
正如在另一条评论中提到的那样,这可能是因为您正在尝试使用的程序是通用 Windows 应用程序。如果您可以让某些程序子集工作,那很可能就是原因。 - hazzey
17
现在是2019年:请使用from PIL import Image代替import Image - Heetola
11
如果你遇到黑框问题,请尝试在PrintWindow中使用不同的数字。在我的情况下,我发现windll.user32.PrintWindow(hwnd, saveDC.GetSafeHdc(), 3)可以打印窗口内容。 - Ignas2526
显示剩余7条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接