【问题标题】:How to take a screenshot of a specific window? (Python)如何截取特定窗口的屏幕截图? (Python)
【发布时间】:2020-12-30 14:42:51
【问题描述】:

所以,我想截取带有特殊标题的特定窗口

我试过这段代码:

import pyautogui
import win32gui

def screenshot(window_title=None):
    if window_title:
        hwnd = win32gui.FindWindow(None, window_title)
        if hwnd:
            win32gui.SetForegroundWindow(hwnd)
            x, y, x1, y1 = win32gui.GetClientRect(hwnd)
            x, y = win32gui.ClientToScreen(hwnd, (x, y))
            x1, y1 = win32gui.ClientToScreen(hwnd, (x1 - x, y1 - y))
            im = pyautogui.screenshot(region=(x, y, x1, y1))
            return im
        else:
            print('Window not found!')
    else:
        im = pyautogui.screenshot()
        return im

if (im := screenshot('Calculator')):
    im.show()

是的,这是可行的,但是如何在不将其置于前台的情况下获取窗口的屏幕截图?

【问题讨论】:

  • 我建议不要将您的 window_title 默认为 None。我不知道这个模块的细节,但如果window_title 不是字符串,FindWindow 很可能会抛出错误。即使没有,也会有这种情况。也许使用"" 作为字符串变量的默认值

标签: python pyautogui win32gui


【解决方案1】:
       
from tkinter import *
import win32gui
import win32ui
from ctypes import windll

def screenshot():

    hwnd = win32gui.FindWindow(None, 'Calculator') #'Calculator' = program name
    
    #left, top, right, bot = win32gui.GetClientRect(hwnd)
    left, top, right, bot = win32gui.GetWindowRect(hwnd) 
    w = right - left #wide
    h = bot - top #hight

    hwndDC = win32gui.GetWindowDC(hwnd)
    mfcDC  = win32ui.CreateDCFromHandle(hwndDC)
    saveDC = mfcDC.CreateCompatibleDC()

    saveBitMap = win32ui.CreateBitmap()
    saveBitMap.CreateCompatibleBitmap(mfcDC, w, h)

    saveDC.SelectObject(saveBitMap)

    #result = windll.user32.PrintWindow(hwnd, saveDC.GetSafeHdc(), 0)
    result = windll.user32.PrintWindow(hwnd, saveDC.GetSafeHdc(), 1)

    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: #if Succeeded
        im.save("C:/Users/Moon/Desktop/test.png") # save path 
     
    else:
        print("Error")

screenshot()

我放了一个计算器。换个路径试试

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-02
    • 1970-01-01
    • 1970-01-01
    • 2017-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多