python窗口操作
参考文献
- python中的窗口操作 简单的窗口操作的集合
- python中键鼠操作 好像没用?
- python模拟键盘操作这个可以用,但是在控制的瞬间需要主动选中窗口 目前没有找到可以用的后台控制的方法,先用这个凑合着
- python获取窗口图像该方法可以获取窗口图像,但是不能在后台截图
- Python后台截图这个方法就完善许多,可以在最小化窗口(win+d)的情况下依然能截图
窗口操作
后台截图
该部分来自Python后台截图
from ctypes import windll, byref, c_ubyte
from ctypes.wintypes import RECT, HWND
import matplotlib.pyplot as plt
import numpy as np
import cv2
GetDC = windll.user32.GetDC
CreateCompatibleDC = windll.gdi32.CreateCompatibleDC
GetClientRect = windll.user32.GetClientRect
CreateCompatibleBitmap = windll.gdi32.CreateCompatibleBitmap
SelectObject = windll.gdi32.SelectObject
BitBlt = windll.gdi32.BitBlt
SRCCOPY = 0x00CC0020
GetBitmapBits = windll.gdi32.GetBitmapBits
DeleteObject = windll.gdi32.DeleteObject
ReleaseDC = windll.user32.ReleaseDC
# 排除缩放干扰
windll.user32.SetProcessDPIAware()
def capture(handle: HWND):
"""窗口客户区截图
Args:
handle (HWND): 要截图的窗口句柄
Returns:
numpy.ndarray: 截图数据
"""
# 获取窗口客户区的大小
r = RECT()
GetClientRect(handle, byref(r))
width, height = r.right, r.bottom
# 开始截图
dc = GetDC(handle)
cdc = CreateCompatibleDC(dc)
bitmap = CreateCompatibleBitmap(dc, width, height)
SelectObject(cdc, bitmap)
BitBlt(cdc, 0, 0, width, height, dc, 0, 0, SRCCOPY)
# 截图是BGRA排列,因此总元素个数需要乘以4
total_bytes = width*height*4
buffer = bytearray(total_bytes)
byte_array = c_ubyte*total_bytes
GetBitmapBits(bitmap, total_bytes, byte_array.from_buffer(buffer))
DeleteObject(bitmap)
DeleteObject(cdc)
ReleaseDC(handle, dc)
# 返回截图数据为numpy.ndarray
return np.frombuffer(buffer, dtype=np.uint8).reshape(height, width, 4)
- 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
键盘控制
import win32api
import win32con
import win32gui
win32gui.SetForegroundWindow(w2hd)
win32api.keybd_event(68,0,0,0)
win32api.keybd_event(68,0,win32con.KEYEVENTF_KEYUP,0) #释放按键
- 1
- 2
- 3
- 4
- 5
- 6