Rust 获取 windows 的剪贴板

196 天前
 techoc
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"
976 次点击
所在节点    Rust
0 条回复

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/1049298

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX