修复 v0.5 审查问题: platform 改名, 协议健壮性, CJK 匹配, VBS 引号, interception API
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+127
-83
@@ -3,11 +3,15 @@
|
|||||||
|
|
||||||
输入在驱动层转为真实 HID 事件(对应用透明,非 SendInput 虚拟输入)。
|
输入在驱动层转为真实 HID 事件(对应用透明,非 SendInput 虚拟输入)。
|
||||||
需要: install-interception.exe /install 后重启系统,且本 dll 与驱动共存。
|
需要: install-interception.exe /install 后重启系统,且本 dll 与驱动共存。
|
||||||
|
|
||||||
|
API 以 oblitum/Interception interception.h 为准:
|
||||||
|
设备号 1..10 = 键盘, 11..20 = 鼠标; 没有 open_device 之类的函数。
|
||||||
|
interception_send(ctx, device, stroke*, nstroke) 第 4 个参数是 stroke 个数, 不是字节数。
|
||||||
"""
|
"""
|
||||||
import ctypes
|
import ctypes
|
||||||
import time
|
import time
|
||||||
|
|
||||||
from ctypes import wintypes
|
from ._util import parse_combo, win_dpi_aware
|
||||||
|
|
||||||
# ---- Interception 常量 ----
|
# ---- Interception 常量 ----
|
||||||
MOUSE_LEFTBUTTON_DOWN = 0x001
|
MOUSE_LEFTBUTTON_DOWN = 0x001
|
||||||
@@ -25,9 +29,12 @@ KEY_DOWN = 0x00
|
|||||||
KEY_UP = 0x01
|
KEY_UP = 0x01
|
||||||
KEY_E0 = 0x02
|
KEY_E0 = 0x02
|
||||||
|
|
||||||
|
MAX_KEYBOARD = 10
|
||||||
|
MAX_MOUSE = 10
|
||||||
|
KEYBOARD_DEVS = range(1, MAX_KEYBOARD + 1)
|
||||||
|
MOUSE_DEVS = range(MAX_KEYBOARD + 1, MAX_KEYBOARD + MAX_MOUSE + 1)
|
||||||
|
|
||||||
# ---- Set 1 扫描码 ----
|
# ---- Set 1 扫描码 ----
|
||||||
SCAN_ALPHA = {chr(c): 0x1E + i for i, c in enumerate(range(ord('A'), ord('Z') + 1))}
|
|
||||||
# 上面的映射只在 A-P 连续,Q-Z 不连续,改为显式表
|
|
||||||
SCAN = {
|
SCAN = {
|
||||||
'a': 0x1E, 'b': 0x30, 'c': 0x2E, 'd': 0x20, 'e': 0x12, 'f': 0x21,
|
'a': 0x1E, 'b': 0x30, 'c': 0x2E, 'd': 0x20, 'e': 0x12, 'f': 0x21,
|
||||||
'g': 0x22, 'h': 0x23, 'i': 0x17, 'j': 0x24, 'k': 0x25, 'l': 0x26,
|
'g': 0x22, 'h': 0x23, 'i': 0x17, 'j': 0x24, 'k': 0x25, 'l': 0x26,
|
||||||
@@ -36,37 +43,59 @@ SCAN = {
|
|||||||
'y': 0x15, 'z': 0x2C,
|
'y': 0x15, 'z': 0x2C,
|
||||||
'1': 0x02, '2': 0x03, '3': 0x04, '4': 0x05, '5': 0x06,
|
'1': 0x02, '2': 0x03, '3': 0x04, '4': 0x05, '5': 0x06,
|
||||||
'6': 0x07, '7': 0x08, '8': 0x09, '9': 0x0A, '0': 0x0B,
|
'6': 0x07, '7': 0x08, '8': 0x09, '9': 0x0A, '0': 0x0B,
|
||||||
'enter': 0x1C, 'return': 0x1C, 'esc': 0x01, 'space': 0x39, 'tab': 0x0F,
|
'enter': 0x1C, 'esc': 0x01, 'space': 0x39, 'tab': 0x0F, 'backspace': 0x0E,
|
||||||
'ctrl': 0x1D, 'alt': 0x38, 'lshift': 0x2A, 'rshift': 0x36, 'shift': 0x2A,
|
'ctrl': 0x1D, 'alt': 0x38, 'lshift': 0x2A, 'rshift': 0x36, 'shift': 0x2A,
|
||||||
'f1': 0x3B, 'f2': 0x3C, 'f3': 0x3D, 'f4': 0x3E, 'f5': 0x3F, 'f6': 0x40,
|
'f1': 0x3B, 'f2': 0x3C, 'f3': 0x3D, 'f4': 0x3E, 'f5': 0x3F, 'f6': 0x40,
|
||||||
'f7': 0x41, 'f8': 0x42, 'f9': 0x43, 'f10': 0x44, 'f11': 0x57, 'f12': 0x58,
|
'f7': 0x41, 'f8': 0x42, 'f9': 0x43, 'f10': 0x44, 'f11': 0x57, 'f12': 0x58,
|
||||||
',': 0x33, '.': 0x34, '/': 0x35, ';': 0x27, "'": 0x28, '[': 0x1A,
|
',': 0x33, '.': 0x34, '/': 0x35, ';': 0x27, "'": 0x28, '[': 0x1A,
|
||||||
']': 0x1B, '-': 0x0C, '=': 0x0D, '`': 0x29, '\\': 0x2B,
|
']': 0x1B, '-': 0x0C, '=': 0x0D, '`': 0x29, '\\': 0x2B,
|
||||||
}
|
}
|
||||||
UPPER_SCAN = { # 大写所需符号的扫描码(按住 Shift 时)
|
# 扩展键: 扫描码同小键盘, 需带 E0 前缀
|
||||||
|
SCAN_E0 = {
|
||||||
|
'up': 0x48, 'down': 0x50, 'left': 0x4B, 'right': 0x4D,
|
||||||
|
'home': 0x47, 'end': 0x4F, 'pageup': 0x49, 'pagedown': 0x51,
|
||||||
|
'insert': 0x52, 'delete': 0x53, 'rctrl': 0x1D, 'ralt': 0x38, 'lwin': 0x5B,
|
||||||
|
}
|
||||||
|
UPPER_SCAN = { # 需按住 Shift 的符号
|
||||||
'!': 0x02, '@': 0x03, '#': 0x04, '$': 0x05, '%': 0x06, '^': 0x07,
|
'!': 0x02, '@': 0x03, '#': 0x04, '$': 0x05, '%': 0x06, '^': 0x07,
|
||||||
'&': 0x08, '*': 0x09, '(': 0x0A, ')': 0x0B, '_': 0x0C, '+': 0x0D,
|
'&': 0x08, '*': 0x09, '(': 0x0A, ')': 0x0B, '_': 0x0C, '+': 0x0D,
|
||||||
'{': 0x1A, '}': 0x1B, ':': 0x27, '"': 0x28, '<': 0x33, '>': 0x34,
|
'{': 0x1A, '}': 0x1B, ':': 0x27, '"': 0x28, '<': 0x33, '>': 0x34,
|
||||||
'?': 0x35, '~': 0x29, '|': 0x2B,
|
'?': 0x35, '~': 0x29, '|': 0x2B,
|
||||||
}
|
}
|
||||||
|
|
||||||
MAX_DEVICES = 64 # 键盘下游设备数量通常 <= 16,鼠标 <= 16;放宽到 64 覆盖异常
|
|
||||||
|
|
||||||
|
|
||||||
class MouseStroke(ctypes.Structure):
|
class MouseStroke(ctypes.Structure):
|
||||||
|
# interception.h: unsigned short state, flags; short rolling; int x, y; unsigned int information
|
||||||
_fields_ = [("state", ctypes.c_ushort), ("flags", ctypes.c_ushort),
|
_fields_ = [("state", ctypes.c_ushort), ("flags", ctypes.c_ushort),
|
||||||
("rolling", ctypes.c_short), ("x", ctypes.c_ulong),
|
("rolling", ctypes.c_short), ("x", ctypes.c_int),
|
||||||
("y", ctypes.c_ulong), ("information", ctypes.c_ulong)]
|
("y", ctypes.c_int), ("information", ctypes.c_uint)]
|
||||||
|
|
||||||
|
|
||||||
class KeyStroke(ctypes.Structure):
|
class KeyStroke(ctypes.Structure):
|
||||||
_fields_ = [("code", ctypes.c_ushort), ("state", ctypes.c_ushort),
|
_fields_ = [("code", ctypes.c_ushort), ("state", ctypes.c_ushort),
|
||||||
("information", ctypes.c_ulong)]
|
("information", ctypes.c_uint)]
|
||||||
|
|
||||||
|
|
||||||
|
def key_strokes(key):
|
||||||
|
"""键名 -> (scancode, e0) ; 未知返回 None。"""
|
||||||
|
if key in SCAN:
|
||||||
|
return SCAN[key], False
|
||||||
|
if key in SCAN_E0:
|
||||||
|
return SCAN_E0[key], True
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def to_absolute(v, size):
|
||||||
|
"""像素 -> Interception 绝对坐标 0..65535 (主屏)。"""
|
||||||
|
if size <= 1:
|
||||||
|
return 0
|
||||||
|
v = min(max(int(v), 0), size - 1)
|
||||||
|
return int(round(v * 65535.0 / (size - 1)))
|
||||||
|
|
||||||
|
|
||||||
class InterceptionBackend:
|
class InterceptionBackend:
|
||||||
|
|
||||||
def __init__(self, dll_path=None):
|
def __init__(self, dll_path=None, keyboard=None, mouse=None):
|
||||||
if dll_path is None:
|
if dll_path is None:
|
||||||
dll_path = r'C:\Program Files\Interception\interception.dll'
|
dll_path = r'C:\Program Files\Interception\interception.dll'
|
||||||
try:
|
try:
|
||||||
@@ -76,69 +105,77 @@ class InterceptionBackend:
|
|||||||
self.dll = ctypes.CDLL('interception.dll')
|
self.dll = ctypes.CDLL('interception.dll')
|
||||||
self._api()
|
self._api()
|
||||||
self._user32 = ctypes.WinDLL('user32', use_last_error=True)
|
self._user32 = ctypes.WinDLL('user32', use_last_error=True)
|
||||||
|
win_dpi_aware(self._user32)
|
||||||
self.ctx = self.dll.interception_create_context()
|
self.ctx = self.dll.interception_create_context()
|
||||||
if not self.ctx:
|
if not self.ctx:
|
||||||
raise RuntimeError('interception_create_context failed (驱动未安装/未重启?)')
|
raise RuntimeError('interception_create_context failed (驱动未安装/未重启?)')
|
||||||
self._kbd_devs, self._mou_devs = self._discover()
|
# 只往一个设备发: 广播到所有键盘会让同一个键被按多次
|
||||||
|
self.kbd = keyboard or self._first_present(KEYBOARD_DEVS)
|
||||||
|
self.mou = mouse or self._first_present(MOUSE_DEVS)
|
||||||
self._scr_w = self._user32.GetSystemMetrics(0)
|
self._scr_w = self._user32.GetSystemMetrics(0)
|
||||||
self._scr_h = self._user32.GetSystemMetrics(1)
|
self._scr_h = self._user32.GetSystemMetrics(1)
|
||||||
|
|
||||||
|
def __del__(self):
|
||||||
|
try:
|
||||||
|
if getattr(self, 'ctx', None):
|
||||||
|
self.dll.interception_destroy_context(self.ctx)
|
||||||
|
self.ctx = None
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
def _api(self):
|
def _api(self):
|
||||||
d = self.dll
|
d = self.dll
|
||||||
d.interception_create_context.restype = ctypes.c_void_p
|
d.interception_create_context.restype = ctypes.c_void_p
|
||||||
d.interception_create_context.argtypes = []
|
d.interception_create_context.argtypes = []
|
||||||
|
d.interception_destroy_context.restype = None
|
||||||
d.interception_destroy_context.argtypes = [ctypes.c_void_p]
|
d.interception_destroy_context.argtypes = [ctypes.c_void_p]
|
||||||
d.interception_open_device.restype = ctypes.c_bool
|
d.interception_get_hardware_id.restype = ctypes.c_uint
|
||||||
d.interception_open_device.argtypes = [ctypes.c_void_p, ctypes.c_int]
|
|
||||||
d.interception_close_device.argtypes = [ctypes.c_void_p, ctypes.c_int]
|
|
||||||
d.interception_get_hardware_id.restype = ctypes.c_int
|
|
||||||
d.interception_get_hardware_id.argtypes = [ctypes.c_void_p, ctypes.c_int,
|
d.interception_get_hardware_id.argtypes = [ctypes.c_void_p, ctypes.c_int,
|
||||||
ctypes.c_char_p, ctypes.c_int]
|
ctypes.c_void_p, ctypes.c_uint]
|
||||||
d.interception_send.restype = ctypes.c_int
|
d.interception_send.restype = ctypes.c_int
|
||||||
d.interception_send.argtypes = [ctypes.c_void_p, ctypes.c_int,
|
d.interception_send.argtypes = [ctypes.c_void_p, ctypes.c_int,
|
||||||
ctypes.c_void_p, ctypes.c_size_t]
|
ctypes.c_void_p, ctypes.c_uint]
|
||||||
|
|
||||||
def _discover(self):
|
def hardware_id(self, dev):
|
||||||
kbd, mou = [], []
|
buf = ctypes.create_string_buffer(512)
|
||||||
buf = ctypes.create_string_buffer(256)
|
n = self.dll.interception_get_hardware_id(self.ctx, dev, buf, ctypes.sizeof(buf))
|
||||||
for dev in range(1, MAX_DEVICES + 1):
|
if not n or n > ctypes.sizeof(buf):
|
||||||
if not self.dll.interception_open_device(self.ctx, dev):
|
return ''
|
||||||
continue
|
# 驱动返回 UTF-16 (REG_MULTI_SZ), 取第一个
|
||||||
n = self.dll.interception_get_hardware_id(self.ctx, dev, buf, 256)
|
return buf.raw[:n].decode('utf-16-le', 'replace').split('\x00')[0]
|
||||||
hid = buf.value.decode('ascii', 'replace').lower() if n > 0 else ''
|
|
||||||
if 'keyboard' in hid:
|
def _first_present(self, devs):
|
||||||
kbd.append(dev)
|
for dev in devs:
|
||||||
elif 'mouse' in hid:
|
if self.hardware_id(dev):
|
||||||
mou.append(dev)
|
return dev
|
||||||
return kbd, mou
|
return devs[0]
|
||||||
|
|
||||||
|
def set_screen(self, w, h):
|
||||||
|
"""以截图尺寸为准(会话 0 / DPI 虚拟化下 GetSystemMetrics 不可信)。"""
|
||||||
|
self._scr_w, self._scr_h = int(w), int(h)
|
||||||
|
|
||||||
# ---- 底层发送 ----
|
# ---- 底层发送 ----
|
||||||
def _kbd_stroke(self, code, state):
|
def _send(self, dev, stroke):
|
||||||
ks = KeyStroke()
|
n = self.dll.interception_send(self.ctx, dev, ctypes.byref(stroke), 1)
|
||||||
ks.code = ctypes.c_ushort(code)
|
if n != 1:
|
||||||
ks.state = ctypes.c_ushort(state)
|
raise RuntimeError('interception_send(dev=%d) returned %d' % (dev, n))
|
||||||
for dev in self._kbd_devs or [1]:
|
|
||||||
try:
|
def _kbd_stroke(self, code, state, e0=False):
|
||||||
self.dll.interception_send(self.ctx, dev, ctypes.byref(ks), ctypes.sizeof(ks))
|
ks = KeyStroke(code=code, state=state | (KEY_E0 if e0 else 0))
|
||||||
except Exception:
|
self._send(self.kbd, ks)
|
||||||
pass
|
|
||||||
|
|
||||||
def _mouse_stroke(self, state=0, flags=0, x=0, y=0):
|
def _mouse_stroke(self, state=0, flags=0, x=0, y=0):
|
||||||
ms = MouseStroke()
|
self._send(self.mou, MouseStroke(state=state, flags=flags, x=int(x), y=int(y)))
|
||||||
ms.state = ctypes.c_ushort(state)
|
|
||||||
ms.flags = ctypes.c_ushort(flags)
|
def _tap(self, code, e0=False, hold=0.04):
|
||||||
ms.x = ctypes.c_ulong(int(x))
|
self._kbd_stroke(code, KEY_DOWN, e0)
|
||||||
ms.y = ctypes.c_ulong(int(y))
|
time.sleep(hold)
|
||||||
for dev in self._mou_devs or [17]:
|
self._kbd_stroke(code, KEY_UP, e0)
|
||||||
try:
|
|
||||||
self.dll.interception_send(self.ctx, dev, ctypes.byref(ms), ctypes.sizeof(ms))
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
|
|
||||||
# ---- 公开动作 ----
|
# ---- 公开动作 ----
|
||||||
def move(self, x, y):
|
def move(self, x, y):
|
||||||
nx = int(int(x) * 65535 / self._scr_w) if self._scr_w else 0
|
nx = to_absolute(x, self._scr_w)
|
||||||
ny = int(int(y) * 65535 / self._scr_h) if self._scr_h else 0
|
ny = to_absolute(y, self._scr_h)
|
||||||
self._mouse_stroke(state=0, flags=MOUSE_MOVE_ABSOLUTE, x=nx, y=ny)
|
self._mouse_stroke(state=0, flags=MOUSE_MOVE_ABSOLUTE, x=nx, y=ny)
|
||||||
time.sleep(0.03)
|
time.sleep(0.03)
|
||||||
return {'ok': True, 'backend': 'interception'}
|
return {'ok': True, 'backend': 'interception'}
|
||||||
@@ -152,44 +189,51 @@ class InterceptionBackend:
|
|||||||
down, up = MOUSE_RIGHTBUTTON_DOWN, MOUSE_RIGHTBUTTON_UP
|
down, up = MOUSE_RIGHTBUTTON_DOWN, MOUSE_RIGHTBUTTON_UP
|
||||||
for _ in range(max(1, int(clicks))):
|
for _ in range(max(1, int(clicks))):
|
||||||
self._mouse_stroke(state=down)
|
self._mouse_stroke(state=down)
|
||||||
time.sleep(0.04)
|
time.sleep(0.06)
|
||||||
self._mouse_stroke(state=up)
|
self._mouse_stroke(state=up)
|
||||||
time.sleep(0.05)
|
time.sleep(0.06)
|
||||||
return {'ok': True, 'clicked': [int(x), int(y)], 'backend': 'interception'}
|
return {'ok': True, 'clicked': [int(x), int(y)], 'backend': 'interception'}
|
||||||
|
|
||||||
def _scancode(self, key):
|
|
||||||
k = str(key).lower()
|
|
||||||
return SCAN.get(k)
|
|
||||||
|
|
||||||
def keypress(self, key):
|
def keypress(self, key):
|
||||||
k = str(key)
|
try:
|
||||||
code = SCAN.get(k.lower())
|
parts = parse_combo(key)
|
||||||
if code is None:
|
except ValueError as e:
|
||||||
|
return {'ok': False, 'error': str(e)}
|
||||||
|
strokes = [key_strokes(p) for p in parts]
|
||||||
|
if None in strokes:
|
||||||
return {'ok': False, 'error': 'unknown key %s' % key}
|
return {'ok': False, 'error': 'unknown key %s' % key}
|
||||||
self._kbd_stroke(code, KEY_DOWN)
|
for code, e0 in strokes[:-1]: # 修饰键按下
|
||||||
time.sleep(0.04)
|
self._kbd_stroke(code, KEY_DOWN, e0)
|
||||||
self._kbd_stroke(code, KEY_UP)
|
time.sleep(0.03)
|
||||||
time.sleep(0.02)
|
self._tap(*strokes[-1])
|
||||||
return {'ok': True, 'key': k, 'backend': 'interception'}
|
for code, e0 in reversed(strokes[:-1]):
|
||||||
|
time.sleep(0.03)
|
||||||
|
self._kbd_stroke(code, KEY_UP, e0)
|
||||||
|
return {'ok': True, 'key': str(key), 'backend': 'interception'}
|
||||||
|
|
||||||
def type_text(self, text):
|
def type_text(self, text):
|
||||||
for ch in str(text):
|
text = str(text)
|
||||||
|
plan = []
|
||||||
|
for ch in text:
|
||||||
low = ch.lower()
|
low = ch.lower()
|
||||||
if ch.isupper() and low in SCAN:
|
if ch == ' ':
|
||||||
self._kbd_stroke(SCAN['shift'], KEY_DOWN)
|
plan.append((SCAN['space'], False))
|
||||||
self._kbd_stroke(SCAN[low], KEY_DOWN)
|
elif ch == '\n':
|
||||||
self._kbd_stroke(SCAN[low], KEY_UP)
|
plan.append((SCAN['enter'], False))
|
||||||
self._kbd_stroke(SCAN['shift'], KEY_UP)
|
elif low in SCAN and len(low) == 1:
|
||||||
elif ch.lower() in SCAN:
|
plan.append((SCAN[low], ch.isupper()))
|
||||||
code = SCAN[low]
|
|
||||||
self._kbd_stroke(code, KEY_DOWN)
|
|
||||||
self._kbd_stroke(code, KEY_UP)
|
|
||||||
elif ch in UPPER_SCAN:
|
elif ch in UPPER_SCAN:
|
||||||
self._kbd_stroke(SCAN['shift'], KEY_DOWN)
|
plan.append((UPPER_SCAN[ch], True))
|
||||||
self._kbd_stroke(UPPER_SCAN[ch], KEY_DOWN)
|
|
||||||
self._kbd_stroke(UPPER_SCAN[ch], KEY_UP)
|
|
||||||
self._kbd_stroke(SCAN['shift'], KEY_UP)
|
|
||||||
else:
|
else:
|
||||||
return {'ok': False, 'error': 'untypable char %r' % ch}
|
# 扫描码只能打 US 布局 ASCII; 中文请用 sendinput 后端(KEYEVENTF_UNICODE)
|
||||||
time.sleep(0.015)
|
return {'ok': False, 'error': 'untypable char %r (interception 只支持 ASCII)' % ch}
|
||||||
return {'ok': True, 'typed': str(text), 'backend': 'interception'}
|
for code, shift in plan:
|
||||||
|
if shift:
|
||||||
|
self._kbd_stroke(SCAN['shift'], KEY_DOWN)
|
||||||
|
time.sleep(0.02)
|
||||||
|
self._tap(code, hold=0.03)
|
||||||
|
if shift:
|
||||||
|
time.sleep(0.02)
|
||||||
|
self._kbd_stroke(SCAN['shift'], KEY_UP)
|
||||||
|
time.sleep(0.03)
|
||||||
|
return {'ok': True, 'typed': text, 'backend': 'interception'}
|
||||||
|
|||||||
Reference in New Issue
Block a user