V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
techoc
V2EX  ›  Rust

Rust 获取 windows 的剪贴板

  •  
  •   techoc · 196 天前 · 976 次点击
    这是一个创建于 196 天前的主题,其中的信息可能已经有所发展或是发生改变。
    use encoding::all::GBK;
    use encoding::Encoding;
    use windows::Win32::Foundation::HWND;
    use windows::Win32::System::DataExchange::{CloseClipboard, GetClipboardData, OpenClipboard};
    
    fn main() {
        unsafe {
            if OpenClipboard(HWND(0)).is_ok() {
                let handle_result = GetClipboardData(1);
                if let Ok(handle) = handle_result {
                    if !handle.is_invalid() {
                        let ptr = handle.0 as *const u8;
                        if !ptr.is_null() {
                            // Read the null-terminated string from the pointer
                            let mut len = 0;
                            while *ptr.add(len) != 0 {
                                len += 1;
                            }
                            let slice = std::slice::from_raw_parts(ptr, len);
                            // let text = std::str::from_utf8(slice).expect("Invalid UTF-8");
                            // let text = String::from_utf8_lossy(slice).to_string();
                            let text = GBK.decode(slice, encoding::DecoderTrap::Ignore);
                            println!("Clipboard content: {:?}", text);
                        }
                    } else {
                        println!("Invalid handle");
                    }
                } else {
                    println!("Failed to get clipboard data");
                }
                CloseClipboard().expect("TODO: panic message");
            } else {
                println!("Failed to open clipboard");
            }
        }
    }
    
    
    [dependencies]
    futures = "0.3.5"
    ferris-says = "0.3.1"
    encoding = "0.2"
    
    [dependencies.windows]
    version = "0.57.0"
    features = ["Data_Xml_Dom", "Win32_Foundation", "Win32_Security", "Win32_System_Threading", "Win32_UI_WindowsAndMessaging", "Win32_System_DataExchange", "Win32_System_Ole", "Win32_UI_Controls", "Win32_UI_Controls_RichEdit"]
    
    [dependencies.windows-sys]
    version = "0.52.0"
    features = ["Win32_UI_WindowsAndMessaging", "Win32_UI_Shell", "Win32_Foundation"]
    
    [dependencies.windows-version]
    version = "0.1"
    
    目前尚无回复
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   1008 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 20ms · UTC 21:08 · PVG 05:08 · LAX 13:08 · JFK 16:08
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.