微信小程序翻页小工具

起因

最近要考无人机理论,电脑刷题发现小程序不适配移动端滑动的逻辑,不能方便翻页 ,遂使用AI神力写了小工具:

代码

Python

代码:

# -*- coding: utf-8 -*-
"""
微信小程序滑动助手(Windows / 零依赖,纯 Python 标准库)

把鼠标放在小程序的滑动区域上,按键盘方向键即可模拟手指滑动:

    ←  左滑        →  右滑        Esc 退出

按键全局有效:脚本运行期间终端可以最小化,把焦点留在小程序窗口即可。
每次滑动结束后鼠标会自动回到滑动前的位置,方便反复操作同一块区域。

用法示例:
    python wechat_swipe.py                 # 鼠标拖拽模式(默认)
    python wechat_swipe.py --mode touch    # 触摸注入模式(mouse 模式不生效时再试)
    python wechat_swipe.py --dist 500      # 滑动距离 500 像素
    python wechat_swipe.py --swap          # 交换 ←/→ 键对应的滑动方向
    python wechat_swipe.py --self-test     # 自检后退出(检查环境/触摸注入可用性)
    python wechat_swipe.py --duration 3    # 运行 3 秒后自动退出(测试用,0=一直运行)

两种模式说明:
    mouse —— 在当前鼠标位置模拟"按下左键 → 平滑横移 → 抬起"。
             PC 微信小程序、微信开发者工具、安卓模拟器一般都会把鼠标
             拖拽转成触摸事件,优先用它,兼容性最好。
    touch  —— 调用系统 InjectTouchInput 注入真实触摸,适合只认触摸、
             不认鼠标拖拽的小程序。此模式不会移动你的真实鼠标光标。

注意:脚本不拦截按键,方向键的击键同时也会传给当前焦点窗口。
如果小程序本身也响应方向键造成干扰,需要"吞键"版本请告诉我。
"""

import argparse
import ctypes
import ctypes.wintypes as wt
import sys
import time
from types import SimpleNamespace

if sys.platform != "win32":
    sys.exit("此脚本仅支持 Windows。")

user32 = ctypes.WinDLL("user32", use_last_error=True)

# ---------------- Win32 常量 ----------------
VK_LEFT = 0x25
VK_RIGHT = 0x27
VK_ESCAPE = 0x1B

MOUSEEVENTF_LEFTDOWN = 0x0002
MOUSEEVENTF_LEFTUP = 0x0004

# 触摸注入相关常量(见 winuser.h)
PT_TOUCH = 5
POINTER_FLAG_INRANGE = 0x00000002
POINTER_FLAG_INCONTACT = 0x00000004
POINTER_FLAG_PRIMARY = 0x00000100
POINTER_FLAG_CONFIDENCE = 0x00000400
POINTER_FLAG_DOWN = 0x00010000
POINTER_FLAG_UPDATE = 0x00020000
POINTER_FLAG_UP = 0x00040000
TOUCH_MASK_CONTACTAREA = 0x00000001
TOUCH_MASK_ORIENTATION = 0x00000002
TOUCH_MASK_PRESSURE = 0x00000004
TOUCH_FEEDBACK_DEFAULT = 0x00000001


# ---------------- 结构体定义 ----------------
class POINTER_INFO(ctypes.Structure):
    _fields_ = [
        ("pointerType", ctypes.c_int32),
        ("pointerId", ctypes.c_uint32),
        ("frameId", ctypes.c_uint32),
        ("pointerFlags", ctypes.c_uint32),
        ("sourceDevice", wt.HANDLE),
        ("hwndTarget", wt.HWND),
        ("ptPixelLocation", wt.POINT),
        ("ptHimetricLocation", wt.POINT),
        ("ptPixelLocationRaw", wt.POINT),
        ("ptHimetricLocationRaw", wt.POINT),
        ("dwTime", ctypes.c_uint32),
        ("historyCount", ctypes.c_uint32),
        ("InputData", ctypes.c_uint8 * 28),
        ("dwKeyStates", ctypes.c_uint32),
        ("PerformanceCount", ctypes.c_uint64),
    ]


class POINTER_TOUCH_INFO(ctypes.Structure):
    _fields_ = [
        ("pointerInfo", POINTER_INFO),
        ("touchFlags", ctypes.c_uint32),
        ("touchMask", ctypes.c_uint32),
        ("rcContact", wt.RECT),
        ("Orientation", ctypes.c_uint32),
        ("Pressure", ctypes.c_uint32),
    ]


# ---------------- API 绑定 ----------------
user32.GetAsyncKeyState.restype = ctypes.c_short
user32.GetAsyncKeyState.argtypes = [ctypes.c_int]
user32.GetCursorPos.argtypes = [ctypes.POINTER(wt.POINT)]
user32.GetCursorPos.restype = wt.BOOL
user32.SetCursorPos.argtypes = [ctypes.c_int, ctypes.c_int]
user32.SetCursorPos.restype = wt.BOOL
user32.mouse_event.argtypes = [ctypes.c_uint32, ctypes.c_uint32,
                               ctypes.c_uint32, ctypes.c_uint32,
                               ctypes.c_size_t]
user32.SetProcessDPIAware.restype = wt.BOOL
user32.InitializeTouchInjection.restype = wt.BOOL
user32.InitializeTouchInjection.argtypes = [ctypes.c_uint32, ctypes.c_ulong]
user32.InjectTouchInput.restype = wt.BOOL
user32.InjectTouchInput.argtypes = [ctypes.c_uint32,
                                    ctypes.POINTER(POINTER_TOUCH_INFO)]

# 高 DPI 屏(125% / 150% 缩放)下保证鼠标坐标不被系统虚拟化
user32.SetProcessDPIAware()


# ---------------- 基础工具 ----------------
def key_pressed(vk: int) -> bool:
    """某虚拟键当前是否处于按下状态(全局)。"""
    return bool(user32.GetAsyncKeyState(vk) & 0x8000)


def mouse_pos():
    pt = wt.POINT()
    if not user32.GetCursorPos(ctypes.byref(pt)):
        raise ctypes.WinError(ctypes.get_last_error())
    return pt.x, pt.y


# ---------------- mouse 模式 ----------------
def swipe_mouse(dx: int, cfg) -> None:
    """在当前鼠标位置模拟一次横向拖拽,dx<0 向左、dx>0 向右。"""
    x0, y = mouse_pos()
    steps = max(8, abs(dx) // 18)          # 每步约 18px,模拟真实滑动
    user32.mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0)
    time.sleep(cfg.press_ms / 1000)
    for i in range(1, steps + 1):
        user32.SetCursorPos(x0 + dx * i // steps, y)
        time.sleep(cfg.step_ms / 1000)
    time.sleep(cfg.release_ms / 1000)
    user32.mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0)
    time.sleep(0.01)
    user32.SetCursorPos(x0, y)             # 抬起后鼠标回到起点


# ---------------- touch 模式 ----------------
_TOUCH_INITED = False


def init_touch() -> None:
    """初始化触摸注入(整个进程只需一次)。"""
    global _TOUCH_INITED
    if _TOUCH_INITED:
        return
    if not user32.InitializeTouchInjection(1, TOUCH_FEEDBACK_DEFAULT):
        raise ctypes.WinError(ctypes.get_last_error())
    _TOUCH_INITED = True


def send_touch(flags: int, x: int, y: int) -> None:
    """注入一帧触摸事件。"""
    info = POINTER_TOUCH_INFO()
    info.pointerInfo.pointerType = PT_TOUCH
    info.pointerInfo.pointerId = 0
    info.pointerInfo.frameId = 0
    info.pointerInfo.pointerFlags = flags
    info.pointerInfo.hwndTarget = None        # 0 = 系统按坐标自动命中窗口
    info.pointerInfo.ptPixelLocation.x = int(x)
    info.pointerInfo.ptPixelLocation.y = int(y)
    info.touchFlags = 0
    info.touchMask = TOUCH_MASK_CONTACTAREA | TOUCH_MASK_ORIENTATION | TOUCH_MASK_PRESSURE
    info.rcContact.left = int(x) - 1
    info.rcContact.top = int(y) - 1
    info.rcContact.right = int(x) + 1
    info.rcContact.bottom = int(y) + 1
    info.Orientation = 90                     # 0~359,90=竖直方向
    info.Pressure = 512                       # 0~1024
    if not user32.InjectTouchInput(1, ctypes.byref(info)):
        raise ctypes.WinError(ctypes.get_last_error())


def swipe_touch(dx: int, cfg) -> None:
    """以当前鼠标位置为触点,注入一次横向触摸滑动。"""
    init_touch()
    x0, y = mouse_pos()
    steps = max(8, abs(dx) // 18)
    base = POINTER_FLAG_PRIMARY | POINTER_FLAG_CONFIDENCE | POINTER_FLAG_INRANGE
    send_touch(base | POINTER_FLAG_DOWN | POINTER_FLAG_INCONTACT, x0, y)
    time.sleep(cfg.press_ms / 1000)
    for i in range(1, steps + 1):
        send_touch(base | POINTER_FLAG_UPDATE | POINTER_FLAG_INCONTACT,
                   x0 + dx * i // steps, y)
        time.sleep(cfg.step_ms / 1000)
    time.sleep(cfg.release_ms / 1000)
    send_touch(base | POINTER_FLAG_UP, x0 + dx, y)


# ---------------- 自检 ----------------
def self_test(mode: str) -> int:
    print("== 自检 ==")
    x, y = mouse_pos()
    print(f"当前鼠标位置: ({x}, {y})")
    if mode == "touch":
        try:
            init_touch()
            print("触摸注入: 可用 ✓")
        except OSError as e:
            print(f"触摸注入: 不可用 ✗ ({e})")
            return 1
    else:
        print("鼠标拖拽: 可用(系统 API,无需初始化)")
    print("自检完成。")
    return 0


# ---------------- 主程序 ----------------
def main(argv=None) -> int:
    p = argparse.ArgumentParser(
        description="微信小程序滑动助手:方向键 ←/→ 模拟左滑/右滑,Esc 退出")
    p.add_argument("--mode", choices=["mouse", "touch"], default="mouse",
                   help="滑动模拟方式,默认 mouse(鼠标拖拽)")
    p.add_argument("--dist", type=int, default=350,
                   help="滑动距离(像素),默认 350")
    p.add_argument("--swap", action="store_true",
                   help="交换 ←/→ 键对应的滑动方向")
    p.add_argument("--step-ms", type=int, default=6,
                   help="滑动时每步移动间隔(毫秒),默认 6;值越小滑动越快")
    p.add_argument("--press-ms", type=int, default=30,
                   help="按下后先停留的时间(毫秒),默认 30")
    p.add_argument("--release-ms", type=int, default=60,
                   help="抬起前停留的时间(毫秒),默认 60")
    p.add_argument("--duration", type=int, default=0,
                   help="运行指定秒数后自动退出(0=一直运行),测试用")
    p.add_argument("--self-test", action="store_true",
                   help="只做自检,不进入监听")
    a = p.parse_args(argv)

    if a.dist < 1:
        p.error("--dist 至少为 1")

    if a.self_test:
        return self_test(a.mode)

    if a.mode == "touch":
        init_touch()

    cfg = SimpleNamespace(step_ms=a.step_ms, press_ms=a.press_ms,
                          release_ms=a.release_ms)
    swipe = swipe_mouse if a.mode == "mouse" else swipe_touch

    left_dx = a.dist if a.swap else -a.dist   # 按下 ← 时的横移距离
    right_dx = -left_dx
    left_name = "右滑" if a.swap else "左滑"
    right_name = "左滑" if a.swap else "右滑"

    print(f"微信小程序滑动助手已启动:模式={a.mode}  距离={a.dist}px  "
          f"映射=← {left_name} / → {right_name}")
    print("把鼠标放到小程序的滑动区域上,按 ← / → 滑动;按 Esc 退出。")

    prev_left = False
    prev_right = False
    start = time.monotonic()
    try:
        while True:
            if key_pressed(VK_ESCAPE):
                print("检测到 Esc,退出。")
                break
            now_left = key_pressed(VK_LEFT)
            now_right = key_pressed(VK_RIGHT)
            if now_left and not prev_left:      # 边沿检测:按下瞬间才触发
                swipe(left_dx, cfg)
                print(f"← {left_name} 完成")
            if now_right and not prev_right:
                swipe(right_dx, cfg)
                print(f"→ {right_name} 完成")
            prev_left, prev_right = now_left, now_right
            if a.duration > 0 and time.monotonic() - start >= a.duration:
                print("到达 --duration 限时,自动退出。")
                break
            time.sleep(0.015)
    except KeyboardInterrupt:
        print("Ctrl+C 退出。")
    return 0


if __name__ == "__main__":
    sys.exit(main())

bat文件

启动脚本:

@echo off
rem Launcher: WeChat mini-program swipe helper (mouse-drag mode)
where python >nul 2>nul
if errorlevel 1 (
    echo Python not found in PATH. Please install Python 3 first.
    pause
    exit /b 1
)
python "%~dp0wechat_swipe.py" %*
pause

愿天下PC端小程序用户可以丝滑翻页

无标签
打赏
评论区
头像
文章目录