当前位置: 首页 > 工具软件 > PythonWin > 使用案例 >

python win32 窗口截图

澹台阳秋
2023-12-01

python win32 窗口截图

获取窗口句柄和标题

import win32gui

hwnd_title = dict()


def _get_all_hwnd(hwnd, mouse):
    if win32gui.IsWindow(hwnd) and win32gui.IsWindowEnabled(hwnd) and win32gui.IsWindowVisible(hwnd):
        hwnd_title.update({hwnd: win32gui.GetWindowText(hwnd)})


win32gui.EnumWindows(_get_all_hwnd, 0)
for wnd in hwnd_title.items():
    print(wnd)

运行结果如下,格式为:(窗口句柄, 窗口标题)
可自行根据标题筛选想要的窗口

(65772, '')
(262798, 'pythonProject – screenShot.py')
(5114244, '项目里程碑.ppt[兼容模式] - PowerPoint')
(3803304, '')
(133646, '')
(133642, '')

根据窗口句柄截图

import win32com.client
import win32gui
import win32api
import win32con
import win32ui
from PIL import Image


def setForeground(hwnd):
    """
        将窗口设置为最前面
    :param hwnd: 窗口句柄 一个整数
    """
    if hwnd != win32gui.GetForegroundWindow():
        shell = win32com.client.Dispatch("WScript.Shell")
        shell.SendKeys('%')
        win32gui.SetForegroundWindow(hwnd)


def winShot(hwnd):
    """
        根据窗口句柄截取窗口视图
    :param hwnd: 窗口句柄 一个整数
    """
    bmpFileName = 'screenshot.bmp'
    jpgFileName = 'screenshot.jpg'

    r = win32gui.GetWindowRect(hwnd)
    hwin = win32gui.GetDesktopWindow()
    # 图片最左边距离主屏左上角的水平距离
    left = win32api.GetSystemMetrics(win32con.SM_XVIRTUALSCREEN)
    # 图片最上边距离主屏左上角的垂直距离
    top = win32api.GetSystemMetrics(win32con.SM_YVIRTUALSCREEN)
    hwindc = win32gui.GetWindowDC(hwin)
    srcdc = win32ui.CreateDCFromHandle(hwindc)
    memdc = srcdc.CreateCompatibleDC()
    bmp = win32ui.CreateBitmap()
    bmp.CreateCompatibleBitmap(srcdc, r[2] - r[0], r[3] - r[1])
    memdc.SelectObject(bmp)
    memdc.BitBlt((-r[0], top - r[1]), (r[2], r[3] - top), srcdc, (left, top), win32con.SRCCOPY)
    bmp.SaveBitmapFile(memdc, bmpFileName)

    im = Image.open(bmpFileName)
    im = im.convert('RGB')
    im.save(jpgFileName)

if __name__ == '__main__':
    setForeground(5114244)
    winShot(5114244)
 类似资料: