python realizes window screenshot based on win32

  • 2021-09-16 07:38:39
  • OfStack

In this paper, we share the specific code of python based on win32 to realize window screenshots for your reference. The specific contents are as follows

Get the window handle and title


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)

The running result is as follows in the format: (window handle, window title)
You can filter the desired window by title


(65772, '')
(262798, 'pythonProject  In fact, in fact, the  screenShot.py')
(5114244, ' Project Milestones .ppt[ Compatibility mode ] - PowerPoint')
(3803304, '')
(133646, '')
(133642, '')

Screenshot according to window handle


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


def setForeground(hwnd):
 """
   Set the window to the front 
 :param hwnd:  Window handle  1 Integer 
 """
 if hwnd != win32gui.GetForegroundWindow():
  shell = win32com.client.Dispatch("WScript.Shell")
  shell.SendKeys('%')
  win32gui.SetForegroundWindow(hwnd)


def winShot(hwnd):
 """
   Intercept the window view according to the window handle 
 :param hwnd:  Window handle  1 Integer 
 """
 bmpFileName = 'screenshot.bmp'
 jpgFileName = 'screenshot.jpg'

 r = win32gui.GetWindowRect(hwnd)
 hwin = win32gui.GetDesktopWindow()
 #  Horizontal distance from the left-most corner of the picture to the upper left corner of the home screen 
 left = win32api.GetSystemMetrics(win32con.SM_XVIRTUALSCREEN)
 #  Vertical distance from the top of the picture to the upper left corner of the home screen 
 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)

Related articles: