FAQ - Help and questions

How do I copy text to the clipboard and read it back in a Rust program?

#clipboard#arboard#desktoppublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

The arboard crate gives a Clipboard value with set_text and get_text, and it also handles images. Create it once, keep it alive, and treat every call as something that can fail. The program passed cargo check on Windows; it was not run, because running it would overwrite the clipboard.

Checked with rustc 1.93.0, Windows 11, arboard 3.7.0; `cargo check` only. Not run (it replaces the clipboard's content); macOS not tested.

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

Answer#

arboard is a clipboard crate for Windows, macOS and Linux. You make a Clipboard, then call set_text to copy and get_text to paste.

Cargo.tomltoml
[dependencies]
arboard = "3"
src/main.rsrust
use arboard::Clipboard;

fn main() -> Result<(), arboard::Error> {
    let mut clipboard = Clipboard::new()?; // keep this value alive while the app runs
    clipboard.set_text("copied from Rust")?;
    let text = clipboard.get_text()?;
    println!("clipboard now holds: {text}");
    Ok(())
}

This compiled (cargo check) with arboard 3.7.0 on Windows 11. It was not executed for this thread, so there is no output to show: running it replaces whatever the person had copied.

Points to design for:

  • Everything returns Result. The clipboard can be locked by another program, hold something that is not text, or be unavailable. get_text on a clipboard that holds an image returns an error; show a message or ignore it, but do not unwrap.
  • Keep one Clipboard. Make it once and store it in your app state rather than creating one per call. The arboard documentation has notes on platforms where the clipboard's content is tied to the program that owns it; read them if you target Linux.
  • Let the toolkit do it when it can. Text boxes in egui, iced and Slint already handle Ctrl+C and Ctrl+V (Cmd on macOS). Use arboard for your own "Copy path" or "Copy result" buttons, or when the toolkit has no clipboard access.
  • Do not paste blindly. Pasted text is untrusted input: check its length and content as you would for a file.

Common mistakes#

  • Dropping the Clipboard immediately after set_text on Linux, which can lose the text. Keep the value alive.
  • Putting a secret on the clipboard and leaving it there. Other programs can read the clipboard.

Can I copy an image?#

arboard has set_image and get_image with an image data structure; check the crate documentation for the format it expects (RGBA bytes with width and height).

Sources#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet