"""Hold the WeChat voice button with real SendInput while capturing mid-hold.""" import ctypes import sys import time from ctypes import wintypes import win32gui import win32ui from PIL import Image H = 197792 user32 = ctypes.WinDLL('user32', use_last_error=True) class MOUSEINPUT(ctypes.Structure): _fields_ = [('dx', wintypes.LONG), ('dy', wintypes.LONG), ('mouseData', wintypes.DWORD), ('dwFlags', wintypes.DWORD), ('time', wintypes.DWORD), ('dwExtraInfo', ctypes.POINTER(ctypes.c_ulong))] class INPUT(ctypes.Structure): class _I(ctypes.Union): _fields_ = [('mi', MOUSEINPUT)] _anonymous_ = ('i',) _fields_ = [('type', wintypes.DWORD), ('i', _I)] def mouse(flag): inp = INPUT() inp.type = 0 inp.mi = MOUSEINPUT(0, 0, 0, flag, 0, None) return user32.SendInput(1, ctypes.byref(inp), ctypes.sizeof(INPUT)) def grab(path): left, top, right, bottom = win32gui.GetWindowRect(H) w, h = right - left, bottom - top dc = win32gui.GetWindowDC(H) mfc = win32ui.CreateDCFromHandle(dc) mem = mfc.CreateCompatibleDC() bmp = win32ui.CreateBitmap() bmp.CreateCompatibleBitmap(mfc, w, h) mem.SelectObject(bmp) ok = ctypes.windll.user32.PrintWindow(H, mem.GetSafeHdc(), 2) info = bmp.GetInfo() img = Image.frombuffer('RGB', (info['bmWidth'], info['bmHeight']), bmp.GetBitmapBits(True), 'raw', 'BGRX', 0, 1) if ok: img.save(path) mfc.DeleteDC() mem.DeleteDC() win32gui.ReleaseDC(H, dc) if __name__ == '__main__': px, py = int(sys.argv[1]), int(sys.argv[2]) secs = float(sys.argv[3]) if len(sys.argv) > 3 else 3.0 left, top, _, _ = win32gui.GetWindowRect(H) cx, cy = win32gui.ClientToScreen(H, (0, 0)) ox, oy = cx - left, cy - top sx, sy = cx + (px - ox), cy + py print('screen', sx, sy) user32.SetCursorPos(sx, sy) time.sleep(0.3) print('down', mouse(0x0002)) time.sleep(0.9) grab(r'C:\Users\GuoAn\AppData\Local\Temp\wx_hold_mid.png') print('mid captured') time.sleep(max(0.0, secs - 0.9)) print('up', mouse(0x0004)) time.sleep(1.2) grab(r'C:\Users\GuoAn\AppData\Local\Temp\wx_hold_end.png') print('end captured')