Python:无需剪贴板获取第三方应用选中文本的技术问询
如何在不覆盖剪贴板的前提下获取第三方应用中选中的文本
完全可行,不需要依赖剪贴板写入操作,直接通过对应操作系统的API读取当前选中的文本即可,不同平台的实现方式如下:
Windows平台
用ctypes调用Windows原生API,直接向当前激活窗口请求选中的文本,不会碰剪贴板:
import ctypes from ctypes import wintypes user32 = ctypes.WinDLL('user32', use_last_error=True) # 定义API参数类型 HWND = wintypes.HWND user32.GetForegroundWindow.restype = HWND user32.GetWindowThreadProcessId.argtypes = [HWND, wintypes.LPDWORD] user32.SendMessageW.argtypes = [HWND, wintypes.UINT, wintypes.WPARAM, wintypes.LPARAM] # 消息常量 WM_GETTEXTLENGTH = 0x000E EM_GETSEL = 0xB0 EM_GETSELTEXT = 0xB1 def get_selected_text(): hwnd = user32.GetForegroundWindow() # 先获取选中区域的起始和结束位置 sel_result = user32.SendMessageW(hwnd, EM_GETSEL, 0, 0) start_pos = sel_result & 0xFFFF end_pos = sel_result >> 16 if start_pos == end_pos: return "" # 无选中文本 # 计算选中文本长度并分配缓冲区 text_length = end_pos - start_pos buffer = ctypes.create_unicode_buffer(text_length + 1) user32.SendMessageW(hwnd, EM_GETSELTEXT, text_length + 1, ctypes.byref(buffer)) return buffer.value
注意:该方法对标准Windows文本控件有效,部分自定义UI控件可能需要调整对应消息类型。
macOS平台
借助pyobjc调用AppKit框架,读取系统的「选中选区」(和剪贴板是独立的):
from AppKit import NSPasteboard, NSString def get_selected_text(): pasteboard = NSPasteboard.generalPasteboard() # 读取选中的文本,不会修改用户剪贴板 selected_items = pasteboard.readObjectsForClasses_options_([NSString], {}) return selected_items[0] if selected_items else ""
先安装依赖:pip install pyobjc
Linux平台
用Xlib读取X11的PRIMARY选区(对应文本选中状态),完全独立于剪贴板:
from Xlib import display, Xatom def get_selected_text(): d = display.Display() primary_selection = d.get_selection_owner(Xatom.PRIMARY) if not primary_selection: return "" # 请求获取选中文本 d.convert_selection(Xatom.PRIMARY, Xatom.STRING, Xatom.SELECTION, 0, 0) d.flush() # 等待系统响应 while True: event = d.next_event() if event.type == Xatom.SelectionNotify: break # 读取返回的文本内容 if event.property: prop = primary_selection.get_full_property(event.property, Xatom.STRING) return prop.value.decode('utf-8') if prop else "" return ""
先安装依赖:pip install python-xlib
实现流程适配
你的onMouseUp监听器触发后,直接调用对应平台的get_selected_text()函数,拿到文本后再执行语言检测和翻译逻辑即可,全程不会覆盖用户剪贴板内容。
内容的提问来源于stack exchange,提问作者MickyB
相关产品推荐
相关产品推荐

