python实现windows窗体截图的三种方式

分别win32ui,pyqt5,PIL
1、windowsapi

import win32con, win32ui, win32gui
    # 获取窗口句柄
handle = win32gui.FindWindow(None,windowsname)
    # 获取窗口DC
hdDC = win32gui.GetWindowDC(handle)
    # 根据句柄创建一个DC
newhdDC = win32ui.CreateDCFromHandle(hdDC)
    # 创建一个兼容设备内存的DC
saveDC = newhdDC.CreateCompatibleDC()
    # 创建bitmap保存图片
saveBitmap = win32ui.CreateBitmap()
    #win32gui.SendMessage(handle, win32con.WM_SYSCOMMAND, win32con.SC_RESTORE, 0)
    # 获取窗口的位置信息
left, top, right, bottom = win32gui.GetWindowRect(handle)
    # 窗口长宽
width = right - left
height = bottom - top
    # bitmap初始化
saveBitmap.CreateCompatibleBitmap(newhdDC, width, height)
saveDC.SelectObject(saveBitmap)
saveDC.BitBlt((0, 0), (width, height), newhdDC, (0, 0), win32con.SRCCOPY)
saveBitmap.SaveBitmapFile(saveDC, filename)

2、pyqt5

import win32con, win32ui, win32gui
from PyQt5.QtWidgets import QApplication
from PyQt5.QtGui import *
handle = win32gui.FindWindow(None,windowsname)
app = QApplication(sys.argv)
    screen = QApplication.primaryScreen()
    img = screen.grabWindow(handle).toImage()
    img.save("screenshot.jpg")

3、PIL

from PIL import ImageGrab
import win32con, win32ui, win32gui
    # 获取窗口句柄
handle = win32gui.FindWindow(None,windowsname)
left, top, right, bottom = win32gui.GetWindowRect(handle)
img_ready = ImageGrab.grab((left, top, right, bottom))
img_ready.save(os.getcwd() + '/pil.png')

你可能感兴趣的:(虚拟机监控)