132 lines
4.5 KiB
Python
132 lines
4.5 KiB
Python
# -*- coding: utf-8 -*-
|
|
"""剪贴板读写(纯 ctypes,不依赖 pyperclip)。
|
|
|
|
桌面自动化里剪贴板有两个关键用途:
|
|
1. 输入中文/长文本:写剪贴板 + Ctrl+V,比逐字发送稳定得多(不受输入法影响);
|
|
2. 读取界面文本:全选复制后读剪贴板,比 OCR 准确(但会覆盖用户剪贴板,用完可 restore)。
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import ctypes
|
|
import time
|
|
from ctypes import wintypes
|
|
from typing import Optional
|
|
|
|
from ._win32 import require_windows
|
|
|
|
CF_UNICODETEXT = 13
|
|
GMEM_MOVEABLE = 0x0002
|
|
|
|
_OPEN_RETRY = 8 # 剪贴板可能被其它进程短暂占用,重试打开
|
|
_OPEN_INTERVAL = 0.03
|
|
|
|
|
|
def _open() -> None:
|
|
"""打开剪贴板(带重试),失败抛错。"""
|
|
user32 = ctypes.windll.user32
|
|
for _ in range(_OPEN_RETRY):
|
|
if user32.OpenClipboard(None):
|
|
return
|
|
time.sleep(_OPEN_INTERVAL)
|
|
raise RuntimeError("打开剪贴板失败(可能被其它程序占用)")
|
|
|
|
|
|
def _close() -> None:
|
|
try:
|
|
ctypes.windll.user32.CloseClipboard()
|
|
except Exception: # noqa: BLE001
|
|
pass
|
|
|
|
|
|
def set_text(text: str) -> None:
|
|
"""把文本写入剪贴板(覆盖原内容)。"""
|
|
require_windows("剪贴板写入")
|
|
kernel32 = ctypes.windll.kernel32
|
|
user32 = ctypes.windll.user32
|
|
kernel32.GlobalAlloc.restype = ctypes.c_void_p
|
|
kernel32.GlobalAlloc.argtypes = [wintypes.UINT, ctypes.c_size_t]
|
|
kernel32.GlobalLock.restype = ctypes.c_void_p
|
|
kernel32.GlobalLock.argtypes = [ctypes.c_void_p]
|
|
kernel32.GlobalUnlock.argtypes = [ctypes.c_void_p]
|
|
user32.SetClipboardData.argtypes = [wintypes.UINT, ctypes.c_void_p]
|
|
user32.SetClipboardData.restype = ctypes.c_void_p
|
|
|
|
data = (str(text) + "\x00").encode("utf-16-le")
|
|
_open()
|
|
handle = None
|
|
try:
|
|
user32.EmptyClipboard()
|
|
handle = kernel32.GlobalAlloc(GMEM_MOVEABLE, len(data))
|
|
if not handle:
|
|
raise RuntimeError("剪贴板内存分配失败")
|
|
ptr = kernel32.GlobalLock(handle)
|
|
if not ptr:
|
|
raise RuntimeError("剪贴板内存锁定失败")
|
|
try:
|
|
ctypes.memmove(ptr, data, len(data))
|
|
finally:
|
|
kernel32.GlobalUnlock(handle)
|
|
if not user32.SetClipboardData(CF_UNICODETEXT, handle):
|
|
raise RuntimeError("写入剪贴板失败")
|
|
handle = None # 所有权已交系统,不能再释放
|
|
finally:
|
|
if handle:
|
|
kernel32.GlobalFree(ctypes.c_void_p(handle))
|
|
_close()
|
|
|
|
|
|
def get_text() -> str:
|
|
"""读取剪贴板文本;剪贴板里没有文本时返回空串(不会抛错)。"""
|
|
require_windows("剪贴板读取")
|
|
kernel32 = ctypes.windll.kernel32
|
|
user32 = ctypes.windll.user32
|
|
user32.GetClipboardData.argtypes = [wintypes.UINT]
|
|
user32.GetClipboardData.restype = ctypes.c_void_p
|
|
kernel32.GlobalLock.restype = ctypes.c_void_p
|
|
kernel32.GlobalLock.argtypes = [ctypes.c_void_p]
|
|
kernel32.GlobalUnlock.argtypes = [ctypes.c_void_p]
|
|
|
|
_open()
|
|
try:
|
|
if not user32.IsClipboardFormatAvailable(CF_UNICODETEXT):
|
|
return ""
|
|
handle = user32.GetClipboardData(CF_UNICODETEXT)
|
|
if not handle:
|
|
return ""
|
|
ptr = kernel32.GlobalLock(ctypes.c_void_p(handle))
|
|
if not ptr:
|
|
return ""
|
|
try:
|
|
return ctypes.wstring_at(ptr) or ""
|
|
finally:
|
|
kernel32.GlobalUnlock(ctypes.c_void_p(handle))
|
|
finally:
|
|
_close()
|
|
|
|
|
|
def paste(text: str, restore: bool = True, delay: float = 0.05) -> str:
|
|
"""写剪贴板 → Ctrl+V 粘贴 →(可选)恢复原剪贴板内容。返回被恢复的原文本。
|
|
|
|
Args:
|
|
text: 要粘贴的文本(中文、长文本都走这条最稳)。
|
|
restore: 粘贴后把剪贴板恢复成原内容,避免污染用户剪贴板。
|
|
delay: 写入剪贴板后等待时间(秒),太短可能粘贴到旧内容。
|
|
"""
|
|
from . import keys # 延迟导入,避免循环依赖
|
|
old: Optional[str] = None
|
|
if restore:
|
|
try:
|
|
old = get_text()
|
|
except Exception: # noqa: BLE001
|
|
old = None
|
|
set_text(text)
|
|
time.sleep(max(0.02, delay))
|
|
keys.hotkey("ctrl", "v")
|
|
if restore and old is not None:
|
|
time.sleep(max(0.05, delay))
|
|
try:
|
|
set_text(old)
|
|
except Exception: # noqa: BLE001
|
|
pass
|
|
return old or ""
|