mouse_control.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. # -*- coding: utf-8 -*-
  2. """Interception 鼠标控制(硬件级相对/绝对移动)。
  3. 依赖:已安装 Interception 驱动 + pip 包 interception-python。
  4. 驱动未装时 move_* 会抛 DriverNotFoundError,上层可降级或直接报错。
  5. """
  6. from __future__ import annotations
  7. import threading
  8. from typing import Optional, Tuple
  9. _lock = threading.Lock()
  10. _ready = False
  11. _last_error: Optional[str] = None
  12. def last_error() -> Optional[str]:
  13. return _last_error
  14. def ensure_ready() -> bool:
  15. """捕获鼠标设备;成功返回 True。可重复调用。"""
  16. global _ready, _last_error
  17. with _lock:
  18. if _ready:
  19. return True
  20. try:
  21. import interception
  22. interception.auto_capture_devices()
  23. # 读一次位置,确认驱动通路活着
  24. interception.mouse_position()
  25. _ready = True
  26. _last_error = None
  27. return True
  28. except Exception as exc:
  29. _ready = False
  30. _last_error = str(exc)
  31. return False
  32. def position() -> Tuple[int, int]:
  33. import interception
  34. return interception.mouse_position()
  35. def move_to(x: int, y: int) -> None:
  36. """绝对移动到屏幕坐标(像素)。"""
  37. if not ensure_ready():
  38. raise RuntimeError(_last_error or "Interception 未就绪")
  39. import interception
  40. interception.move_to(int(x), int(y))
  41. def move_relative(dx: int, dy: int) -> None:
  42. """相对当前光标移动。"""
  43. if not ensure_ready():
  44. raise RuntimeError(_last_error or "Interception 未就绪")
  45. if dx == 0 and dy == 0:
  46. return
  47. import interception
  48. interception.move_relative(int(dx), int(dy))
  49. def follow_screen_point(
  50. sx: float,
  51. sy: float,
  52. *,
  53. gain: float = 1.0,
  54. deadzone: float = 1.5,
  55. max_step: float = 0.0,
  56. ) -> Tuple[int, int]:
  57. """把鼠标朝屏幕点 (sx, sy) 拉过去。
  58. gain=1 且 max_step=0:每帧尽量一次到位(跟着红准星跑)。
  59. 返回本次实际相对位移 (dx, dy)。
  60. """
  61. cx, cy = position()
  62. dx = (float(sx) - cx) * float(gain)
  63. dy = (float(sy) - cy) * float(gain)
  64. if abs(dx) < deadzone and abs(dy) < deadzone:
  65. return (0, 0)
  66. if max_step and max_step > 0:
  67. mag = (dx * dx + dy * dy) ** 0.5
  68. if mag > max_step:
  69. scale = max_step / mag
  70. dx *= scale
  71. dy *= scale
  72. idx, idy = int(round(dx)), int(round(dy))
  73. if idx == 0 and idy == 0:
  74. # 亚像素误差:至少挪 1px 朝目标靠
  75. if abs(sx - cx) >= abs(sy - cy):
  76. idx = 1 if sx > cx else -1
  77. else:
  78. idy = 1 if sy > cy else -1
  79. move_relative(idx, idy)
  80. return (idx, idy)