本文实例为大家分享了python基于win32实现窗口截图的具体代码,供大家参考,具体内容如下
获取窗口句柄和标题
1
2
3
4
5
6
7
8
9
10
11
12
13
|
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)
|
运行结果如下,格式为:(窗口句柄, 窗口标题)
可自行根据标题筛选想要的窗口
1
2
3
4
5
6
|
(65772, '' )
(262798, 'pythonProject – screenShot.py' )
(5114244, '项目里程碑.ppt[兼容模式] - PowerPoint' )
(3803304, '' )
(133646, '' )
(133642, '' )
|
根据窗口句柄截图
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
|
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 )
|
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/BDawn/article/details/112031941