win32系列模块是python windows api实现,效率很高,但是环境搭建比较麻烦,各种pip install报错,本次成功安装依赖idea的Alt + Enter自动下载安装
import win32gui
import win32ui
import win32con
import win32api
def window_capture(filename):
hwndDC = win32gui.GetWindowDC(0) # 0表示当前活跃的窗口
mfcDC = win32ui.CreateDCFromHandle(hwndDC)
saveDC = mfcDC.CreateCompatibleDC()
saveBitMap = win32ui.CreateBitmap()
MoniterDev = win32api.EnumDisplayMonitors(None, None)
w = MoniterDev[0][2][2]
h = MoniterDev[0][2][3]
saveBitMap.CreateCompatibleBitmap(mfcDC, w, h)
saveDC.SelectObject(saveBitMap)
# 截取从左上角(0, 0)长宽为(w, h)的图片
saveDC.BitBlt((0, 0), (w, h), mfcDC, (0, 0), win32con.SRCCOPY)
saveBitMap.SaveBitmapFile(saveDC, filename)
window_capture("testa.png")