-
Notifications
You must be signed in to change notification settings - Fork 0
/
webshot.py
82 lines (62 loc) · 2.2 KB
/
webshot.py
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
"""
webshot.py - screen shot a window
http://stackoverflow.com/q/3586046/1072212
Terry N Brown, [email protected], Fri Nov 18 13:31:59 2016
"""
import os
import re
import sys
import win32con
import win32gui
import win32ui
def numbered_file(fname):
"""Process '%04d' etc. in fname to next non-existent file"""
if not re.search('%.*d', fname):
return fname
for i in range(1, 10000):
if os.path.exists(fname % i):
continue
break
else:
raise Exception("%d plus images, limit reached" % i)
return fname % i
def do_shot(window_pattern, bmpfilenamename, top, left, bottom, right):
bmpfilenamename = numbered_file(bmpfilenamename)
window_re = re.compile(window_pattern)
def callback(hwnd, main):
"""from win32gui.EnumWindows, per window handle (hwnd)"""
text = (win32gui.GetWindowText(hwnd))
if window_re.search(text) and win32gui.IsWindowVisible(hwnd):
windows.append(hwnd)
windows = []
win32gui.EnumWindows(callback, 0)
if not windows:
print("Didn't find window matching '%s'" % window_pattern)
exit(1)
if len(windows) > 1:
print("NOTE: %d windows matched '%s'" % (len(windows), window_pattern))
hwnd = windows[0]
rect = win32gui.GetWindowRect(hwnd)
x = rect[0]
y = rect[1]
w = rect[2] - x - left - right
h = rect[3] - y - top - bottom
wDC = win32gui.GetWindowDC(hwnd)
dcObj = win32ui.CreateDCFromHandle(wDC)
cDC = dcObj.CreateCompatibleDC()
dataBitMap = win32ui.CreateBitmap()
dataBitMap.CreateCompatibleBitmap(dcObj, w, h)
cDC.SelectObject(dataBitMap)
cDC.BitBlt((0, 0), (w, h) , dcObj, (left, top), win32con.SRCCOPY)
dataBitMap.SaveBitmapFile(cDC, bmpfilenamename)
# Free Resources
dcObj.DeleteDC()
cDC.DeleteDC()
win32gui.ReleaseDC(hwnd, wDC)
win32gui.DeleteObject(dataBitMap.GetHandle())
def main():
window_pattern, bmpfilenamename = sys.argv[1:3]
top, left, bottom, right = map(int, sys.argv[3:7])
do_shot(window_pattern, bmpfilenamename, top, left, bottom, right)
if __name__ == '__main__':
main()