基于mss的高性能截图工具

概述

  1. 支持指定程序截图
  2. 支持指定程序截取窗口特定区域
  3. 支持指定程序仅在前台时开始截图
  4. 支持指定程序全屏时截图
  5. 支持自定义截图名称和位置
  6. 支持自定义截图间隔

代码示例

import mss
import win32gui
import os
import time
from pygetwindow import getWindowsWithTitle

window_name = "1.txt - 记事本"  # 指定要截图的窗口名
interval = 1  # 自定义截图间隔

right_shift = 720  # 向右偏移的像素值
down_shift = 30  # 向下偏移的像素值
area_width = 480  # 区域宽度
area_height = 600  # 区域高度


def ensure_window_foreground(window_title, retry_interval=2):
    """确保窗口在前台,如果找不到则等待并重试"""
    while True:
        windows = getWindowsWithTitle(window_title)
        if windows:
            win = windows[0]
            if not win.isActive:  # 判断窗口是否处于活动状态(即前台)
                print(f"窗口 '{window_title}' 不在前台,{retry_interval} 秒后重试")  # 新增打印信息
                time.sleep(retry_interval)  # 等待指定的时间间隔
                continue  # 继续下一次循环
            win.activate()
            break
        else:
            print(f"无法找到标题为'{window_title}'的窗口,{retry_interval}秒后将重试...")
            time.sleep(retry_interval)


def find_unique_filename(output_dir, prefix, extension):
    """找到一个唯一的文件名,避免覆盖现有文件"""
    files = [f for f in os.listdir(output_dir) if f.startswith(prefix) and f.endswith(extension)]
    file_count = len(files) + 1
    return f"{prefix}_{file_count:04d}{extension}"


def get_window_handle(window_name):
    return win32gui.FindWindow(None, window_name)


def get_window_rect(hwnd):
    rect = win32gui.GetWindowRect(hwnd)
    top_left_corner_x, top_left_corner_y, lower_right_corner_x, lower_right_corner_y = rect

    new_top_left_corner_x = top_left_corner_x + right_shift  # 偏移后的左上角的x坐标
    new_top_left_corner_y = top_left_corner_y + down_shift  # 偏移后的左上角的y坐标
    new_lower_right_corner_x = new_top_left_corner_x + area_width  # 偏移后的右下角的x坐标
    new_lower_right_corner_y = new_top_left_corner_y + area_height  # 偏移后的右下角的y坐标

    return new_top_left_corner_x, new_top_left_corner_y, new_lower_right_corner_x, new_lower_right_corner_y


def take_screenshot(window_title, interval, output_base_dir="."):
    output_dir = os.path.join(output_base_dir, "screenshot")
    os.makedirs(output_dir, exist_ok=True)

    hwnd = get_window_handle(window_name)
    if hwnd != 0:
        try:
            while True:
                try:
                    with mss.mss() as sct:
                        while True:
                            ensure_window_foreground(window_title)
                            area = get_window_rect(hwnd)
                            area_shot = sct.grab(area)
                            filename = find_unique_filename(output_dir, "pic", ".png")
                            mss.tools.to_png(area_shot.rgb, area_shot.size, output=os.path.join(output_dir, filename))
                            print(f"已保存截图至: {os.path.abspath(os.path.join(output_dir, filename))}")
                            time.sleep(interval)
                except Exception as e:
                    print(f"截图过程中发生错误: {e}, 将在{interval}秒后重试...")
        except KeyboardInterrupt:
            print("\n手动中断,程序即将退出。")
    else:
        print("未找到指定窗口")


if __name__ == "__main__":
    take_screenshot(window_name, interval)
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值