Xz's blog Xz's blog
首页
时间序列
多模态
合成生物学
其他方向
生活
工具相关
PyTorch
导航站

Xu Zhen

首页
时间序列
多模态
合成生物学
其他方向
生活
工具相关
PyTorch
导航站
  • Rust

  • Rust-Windows 窗口自动化

    • 打印所有用户界面元素
    • 获取并打印单个 UI 元素的特定属性
    • 模拟键盘输入
    • 捕获选择的文本
  • Tauri

  • C++

  • Claude Code

  • Liunx相关

  • Windows相关

  • IDE

  • Conda

  • Docker

  • VMware虚拟机

  • Python常用代码片段

  • 工具相关
  • Rust-Windows 窗口自动化
xuzhen
2025-08-18

捕获选择的文本

use std::thread;  
use std::time::Duration;  
use uiautomation::patterns::UITextPattern;  
use uiautomation::UIAutomation;  
use uiautomation::Result;  
  
/// 捕获当前选中的文本  
fn get_selected_text() -> Result<Vec<String>> {  
    // 1. 初始化 UI Automation    let automation = UIAutomation::new()?;  
  
    // 2. 获取当前拥有焦点的元素  
    let element = automation.get_focused_element()?;  
  
    // 3. 使用通用的 get_pattern 方法,并通过泛型参数指定需要 UITextPattern    if let Ok(text_pattern) = element.get_pattern::<UITextPattern>() {  
        // 4. 获取选中的文本范围集合  
        let selection = text_pattern.get_selection()?;  
        let mut selected_texts = Vec::new();  
  
        // 5. 遍历所有选中的范围并提取文本  
        for range in selection {  
            selected_texts.push(range.get_text(-1)?); // -1 表示获取全部文本  
        }  
        return Ok(selected_texts);  
    }  
  
    // 如果元素不支持 UITextPattern 或没有文本被选中,则返回空Vec  
    Ok(Vec::new())  
}  
  
fn main() {  
    println!("程序已启动,开始每秒轮询一次选中的文本...");  
    println!("请在任意支持的程序中选择文本来查看效果。(按 Ctrl+C 退出)");  
  
    // 用于存储上一次成功捕获的文本,以避免重复打印  
    let mut last_captured_text: Vec<String> = Vec::new();  
  
    // 启动无限循环  
    loop {  
        match get_selected_text() {  
            Ok(current_texts) => {  
                // 检查捕获到的文本是否非空,并且与上一次的不同  
                if !current_texts.is_empty() && current_texts != last_captured_text {  
                    println!("\n[{} UTC] 成功捕获到新的选中文本:", chrono::Utc::now().format("%T"));  
                    for (i, text) in current_texts.iter().enumerate() {  
                        println!("  片段 {}: {}", i + 1, text);  
                    }  
                    // 更新“上一次的文本”  
                    last_captured_text = current_texts;  
                }  
            }  
            Err(e) => {  
                // 如果在获取焦点元素等步骤出错,打印错误信息  
                // 注意:当没有窗口获得焦点时,get_focused_element() 会返回错误,这是正常现象  
                // eprintln!("轮询时发生错误: {:?}", e);  
            }  
        }  
  
        // 线程休眠1秒,实现轮询间隔  
        thread::sleep(Duration::from_secs(1));  
    }  
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#Rust
上次更新: 2025/08/21, 15:38:56

← 模拟键盘输入 WebView→

最近更新
01
Linux 通过Windows代理上网
09-18
02
vscode远程使用copilot和codex(内网环境)
09-18
03
跨机器克隆环境
09-18
更多文章>
Theme by Vdoing | Copyright © 2025-2025 Xu Zhen | 鲁ICP备2025169719号
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式