### Install XCap Native Dependencies on Linux Source: https://context7.com/nashaofu/xcap/llms.txt Lists native package installation commands for Debian/Ubuntu, Alpine, and Arch Linux systems. ```sh # Debian / Ubuntu apt-get install pkg-config libclang-dev libxcb1-dev libxrandr-dev \ libdbus-1-dev libpipewire-0.3-dev libwayland-dev libegl-dev # Alpine apk add pkgconf llvm19-dev clang19-dev libxcb-dev libxrandr-dev \ dbus-dev pipewire-dev wayland-dev mesa-dev # Arch Linux pacman -S base-devel clang libxcb libxrandr dbus libpipewire ``` -------------------------------- ### Record Screen Activity Source: https://github.com/nashaofu/xcap/blob/master/README.md Records a portion of the screen for a specified duration and processes frames. This example demonstrates starting and stopping the screen recorder multiple times. ```rust use std::{thread, time::Duration}; use xcap::Monitor; fn main() { let monitor = Monitor::from_point(100, 100).unwrap(); let (video_recorder, sx) = monitor.video_recorder().unwrap(); thread::spawn(move || loop { match sx.recv() { Ok(frame) => { println!("frame: {:?}", frame.width); } _ => continue, } }); println!("start"); video_recorder.start().unwrap(); thread::sleep(Duration::from_secs(2)); println!("stop"); video_recorder.stop().unwrap(); thread::sleep(Duration::from_secs(2)); println!("start"); video_recorder.start().unwrap(); thread::sleep(Duration::from_secs(2)); println!("stop"); video_recorder.stop().unwrap(); } ``` -------------------------------- ### VideoRecorder::start / VideoRecorder::stop Source: https://context7.com/nashaofu/xcap/llms.txt Controls the screen recording session. `start()` begins delivering frames, and `stop()` halts delivery. ```APIDOC ## VideoRecorder::start / VideoRecorder::stop ### Description `start()` begins delivering `Frame` values into the channel; `stop()` halts delivery. Both methods return `XCapResult<()>`. `VideoRecorder` is `Clone`, so the handle may be shared across threads. ### Methods - **start()**: Begins delivering frames. - **stop()**: Halts frame delivery. ### Returns - `XCapResult<()>` - Indicates success or failure of the operation. ``` -------------------------------- ### Control Recording Session with Start/Stop Source: https://context7.com/nashaofu/xcap/llms.txt Starts and stops a screen recording session, controlling frame delivery. The `VideoRecorder` handle is cloneable for multi-threaded use. Requires `xcap::Monitor` and `std::sync::Arc`. ```rust use std::{sync::{Arc, atomic::{AtomicBool, Ordering}}, thread, time::Duration}; use xcap::Monitor; fn main() { let monitor = Monitor::all().unwrap().into_iter() .find(|m| m.is_primary().unwrap_or(false)) .unwrap(); let (recorder, rx) = monitor.video_recorder().unwrap(); let running = Arc::new(AtomicBool::new(true)); let running_clone = Arc::clone(&running); thread::spawn(move || { let mut count = 0usize; while running_clone.load(Ordering::Relaxed) { if let Ok(_frame) = rx.recv_timeout(Duration::from_millis(100)) { count += 1; } } println!("total frames received: {}", count); }); recorder.start().expect("start failed"); thread::sleep(Duration::from_secs(3)); recorder.stop().expect("stop failed"); running.store(false, Ordering::Relaxed); } ``` -------------------------------- ### Enumerate All Visible Windows with XCap Source: https://context7.com/nashaofu/xcap/llms.txt Lists all open windows sorted by Z-order. Minimized windows are included but may fail to capture. Requires the `xcap` crate. ```rust use xcap::Window; fn main() { let windows = Window::all().expect("failed to enumerate windows"); for w in &windows { println!( "id={} pid={} app={:?} title={:?} monitor={:?} \ pos=({},{},{}) size={}x{} minimized={} maximized={} focused={}", w.id().unwrap(), w.pid().unwrap(), w.app_name().unwrap(), w.title().unwrap(), w.current_monitor().unwrap().friendly_name().unwrap(), w.x().unwrap(), w.y().unwrap(), w.z().unwrap(), w.width().unwrap(), w.height().unwrap(), w.is_minimized().unwrap(), w.is_maximized().unwrap(), w.is_focused().unwrap(), ); } // Example output: // id=1024 pid=891 app="Safari" title="XCap – GitHub" monitor="Built-in Retina Display" // pos=(200,150,0) size=1440x900 minimized=false maximized=false focused=true } ``` -------------------------------- ### Window::all Source: https://context7.com/nashaofu/xcap/llms.txt Enumerates all currently open windows, sorted by Z-order. Minimized windows are included but may not be capturable. ```APIDOC ## `Window::all` — Enumerate All Visible Windows Returns all open windows sorted by Z-order (front-to-back). Minimized windows are included in the list but their `capture_image()` call will fail or return a blank image depending on the platform. ```rust use xcap::Window; fn main() { let windows = Window::all().expect("failed to enumerate windows"); for w in &windows { println!( "id={} pid={} app={:?} title={:?} monitor={:?} \n pos=({},{},{}) size={}x{} minimized={} maximized={} focused={}", w.id().unwrap(), w.pid().unwrap(), w.app_name().unwrap(), w.title().unwrap(), w.current_monitor().unwrap().friendly_name().unwrap(), w.x().unwrap(), w.y().unwrap(), w.z().unwrap(), w.width().unwrap(), w.height().unwrap(), w.is_minimized().unwrap(), w.is_maximized().unwrap(), w.is_focused().unwrap(), ); } // Example output: // id=1024 pid=891 app="Safari" title="XCap – GitHub" monitor="Built-in Retina Display" // pos=(200,150,0) size=1440x900 minimized=false maximized=false focused=true } ``` ``` -------------------------------- ### Monitor::video_recorder Source: https://context7.com/nashaofu/xcap/llms.txt Initializes a video recorder for live screen recording. Returns a `VideoRecorder` handle and a `Receiver` for `Frame` data. ```APIDOC ## Monitor::video_recorder ### Description Returns a `(VideoRecorder, Receiver)` pair. `Frame` carries raw RGBA pixels plus `width` and `height` fields. Call `VideoRecorder::start()` / `VideoRecorder::stop()` to control recording; frames are delivered through the `Receiver` on a background thread. The recorder can be started and stopped multiple times. ### Returns - `Result<(VideoRecorder, Receiver), XCapError>` - A tuple containing the `VideoRecorder` and a `Receiver` for `Frame` data. ``` -------------------------------- ### Capture All Windows Source: https://github.com/nashaofu/xcap/blob/master/README.md Iterates through all available windows, captures an image of each non-minimized window, and saves them to disk. It prints window titles and dimensions. Requires the 'fs_extra' crate. ```rust use fs_extra::dir; use std::time::Instant; use xcap::Window; fn normalized(filename: &str) -> String { filename.replace(['|', '\\', ':', '/'], "") } fn main() { let start = Instant::now(); let windows = Window::all().unwrap(); dir::create_all("target/windows", true).unwrap(); let mut i = 0; for window in windows { // 最小化的窗口不能截屏 if window.is_minimized().unwrap() { continue; } println!( "Window: {:?} {:?} {:?}", window.title().unwrap(), ( window.x().unwrap(), window.y().unwrap(), window.width().unwrap(), window.height().unwrap() ), ( window.is_minimized().unwrap(), window.is_maximized().unwrap() ) ); let image = window.capture_image().unwrap(); image .save(format!( "target/windows/window-{}-{}.png", i, normalized(&window.title().unwrap()) )) .unwrap(); i += 1; } println!("运行耗时: {:?}", start.elapsed()); } ``` -------------------------------- ### Capture All Monitors Source: https://github.com/nashaofu/xcap/blob/master/README.md Captures an image from each connected monitor and saves them to disk. Ensure the 'target/monitors' directory exists. ```rust use fs_extra::dir; use std::time::Instant; use xcap::Monitor; fn normalized(filename: String) -> String { filename.replace(['|', '\\', ':', '/'], "") } fn main() { let start = Instant::now(); let monitors = Monitor::all().unwrap(); dir::create_all("target/monitors", true).unwrap(); for monitor in monitors { let image = monitor.capture_image().unwrap(); image .save(format!( "target/monitors/monitor-{}.png", normalized(monitor.friendly_name().unwrap()) )) .unwrap(); } println!("运行耗时: {:?}", start.elapsed()); } ``` -------------------------------- ### Live Screen Recording with Frame Receiver Source: https://context7.com/nashaofu/xcap/llms.txt Initializes a video recorder and a receiver for raw RGBA frames. Frames are delivered on a background thread. Requires `xcap::Monitor` and `std::thread`. ```rust use std::{thread, time::Duration}; use xcap::{Monitor, image::RgbaImage}; fn main() { std::fs::create_dir_all("target").unwrap(); let monitor = Monitor::from_point(0, 0).unwrap(); let (recorder, rx) = monitor.video_recorder().expect("recorder init failed"); // Consume frames on a dedicated thread. thread::spawn(move || { let mut saved = false; while let Ok(frame) = rx.recv() { println!("frame {}x{} ({} bytes)", frame.width, frame.height, frame.raw.len()); // Save only the very first frame as a PNG. if !saved { RgbaImage::from_raw(frame.width, frame.height, frame.raw) .unwrap() .save("target/first_frame.png") .unwrap(); saved = true; } } }); // Record for 2 s, pause, then record for another 2 s. recorder.start().unwrap(); thread::sleep(Duration::from_secs(2)); recorder.stop().unwrap(); thread::sleep(Duration::from_secs(1)); // brief pause recorder.start().unwrap(); thread::sleep(Duration::from_secs(2)); recorder.stop().unwrap(); } ``` -------------------------------- ### Capture Full-Screen Screenshot with Monitor::capture_image Source: https://context7.com/nashaofu/xcap/llms.txt Captures a full-screen screenshot of a specified monitor and returns it as an `image::RgbaImage`. The image dimensions correspond to the monitor's reported pixel width and height. This image can be saved using various codecs from the `image` crate. ```rust use std::time::Instant; use xcap::Monitor; fn sanitize(name: String) -> String { name.replace(['|', '\\', ':', '/', '"'], "") } fn main() { std::fs::create_dir_all("target/monitors").unwrap(); let start = Instant::now(); for monitor in Monitor::all().unwrap() { let img = monitor.capture_image().expect("capture failed"); let path = format!( "target/monitors/monitor-{}.png", sanitize(monitor.friendly_name().unwrap()) ); img.save(&path).unwrap(); println!("saved {} ({}x{}) in {:?}", path, img.width(), img.height(), start.elapsed()); } // Output: saved target/monitors/monitor-Built-in Retina Display.png (3456x2234) in 45ms } ``` -------------------------------- ### Enumerate All Connected Displays with Monitor::all Source: https://context7.com/nashaofu/xcap/llms.txt Retrieves a vector of all connected monitors. Each monitor's properties like ID, name, position, size, scale factor, and primary status can be accessed. ```rust use xcap::Monitor; fn main() { let monitors = Monitor::all().expect("failed to enumerate monitors"); for monitor in &monitors { println!( "id={} name={:?} friendly={:?} pos=({}, {}) size={}x{} \ rotation={} scale={} freq={} Hz primary={} builtin={}", monitor.id().unwrap(), monitor.name().unwrap(), monitor.friendly_name().unwrap(), monitor.x().unwrap(), monitor.y().unwrap(), monitor.width().unwrap(), monitor.height().unwrap(), monitor.rotation().unwrap(), // 0 | 90 | 180 | 270 degrees monitor.scale_factor().unwrap(), // e.g. 2.0 on HiDPI / Retina monitor.frequency().unwrap(), // e.g. 60.0 or 120.0 monitor.is_primary().unwrap(), monitor.is_builtin().unwrap(), ); } // Example output (macOS 14" MacBook Pro): // id=1 name="Built-in Retina Display" friendly="Built-in Retina Display" // pos=(0, 0) size=3456x2234 rotation=0 scale=2 freq=120 Hz primary=true builtin=true } ``` -------------------------------- ### Poll for Currently Focused Window with XCap Source: https://context7.com/nashaofu/xcap/llms.txt Continuously checks for the window that currently has keyboard focus. Requires polling in a loop as `Window::all()` provides a snapshot. Includes a delay to allow user to switch windows. ```rust use std::{thread, time::Duration}; use xcap::Window; fn main() { // Give the user 3 s to switch to the window they want to track. thread::sleep(Duration::from_secs(3)); loop { if let Ok(windows) = Window::all() { for w in windows.iter().filter(|w| w.is_focused().unwrap_or(false)) { println!( "focused: {:?} (app={:?}, pos=({},{}), size={}x{})", w.title().unwrap(), w.app_name().unwrap(), w.x().unwrap(), w.y().unwrap(), w.width().unwrap(), w.height().unwrap(), ); } } thread::sleep(Duration::from_secs(1)); } } ``` -------------------------------- ### Capture Image of a Single Window with XCap Source: https://context7.com/nashaofu/xcap/llms.txt Captures a screenshot of a specified window. Ensure the window is not minimized before attempting capture. Saves images to the 'target/windows' directory. ```rust use xcap::Window; fn sanitize(s: &str) -> String { s.replace(['|', '\\', ':', '/', '"'], "") } fn main() { std::fs::create_dir_all("target/windows").unwrap(); let windows = Window::all().unwrap(); let mut saved = 0usize; for (i, window) in windows.iter().enumerate() { if window.is_minimized().unwrap_or(true) { continue; // skip — minimized windows cannot be captured } match window.capture_image() { Ok(img) => { let path = format!( "target/windows/window-{}-{}.png", i, sanitize(&window.title().unwrap_or_default()) ); img.save(&path).unwrap(); println!("saved {} ({}x{})", path, img.width(), img.height()); saved += 1; } Err(e) => eprintln!("skipping window {}: {}", i, e), } } println!("captured {} window(s)", saved); } ``` -------------------------------- ### Polling for the Currently Focused Window Source: https://context7.com/nashaofu/xcap/llms.txt Demonstrates how to continuously check which window has keyboard focus using `Window::is_focused()` in a loop. ```APIDOC ## Polling for the Currently Focused Window `Window::is_focused()` returns whether the window currently has keyboard focus. Since `Window::all()` returns a snapshot, poll in a loop to track focus changes in real time. ```rust use std::{thread, time::Duration}; use xcap::Window; fn main() { // Give the user 3 s to switch to the window they want to track. thread::sleep(Duration::from_secs(3)); loop { if let Ok(windows) = Window::all() { for w in windows.iter().filter(|w| w.is_focused().unwrap_or(false)) { println!( "focused: {:?} (app={:?}, pos=({},{}), size={}x{})", w.title().unwrap(), w.app_name().unwrap(), w.x().unwrap(), w.y().unwrap(), w.width().unwrap(), w.height().unwrap(), ); } } thread::sleep(Duration::from_secs(1)); } } ``` ``` -------------------------------- ### Unified Error Handling with XCapError and XCapResult Source: https://context7.com/nashaofu/xcap/llms.txt Demonstrates handling `XCapResult` which can be `XCapError::NotSupported`, `XCapError::Error(String)`, or `XCapError::InvalidCaptureRegion(String)`. Platform-specific errors are wrapped. ```rust use xcap::{Monitor, XCapError}; fn capture_primary() -> Result<(), XCapError> { let monitor = Monitor::all()? .into_iter() .find(|m| m.is_primary().unwrap_or(false)) .ok_or_else(|| XCapError::new("no primary monitor found"))?; // Attempt to capture an obviously out-of-bounds region. let result = monitor.capture_region(0, 0, u32::MAX, u32::MAX); match result { Ok(_) => println!("capture succeeded (unexpected)"), Err(XCapError::InvalidCaptureRegion(msg)) => { println!("region out of bounds: {}", msg); } Err(XCapError::NotSupported) => { println!("operation not supported on this platform"); } Err(e) => { println!("other error: {}", e); return Err(e); } } Ok(()) } fn main() { if let Err(e) = capture_primary() { eprintln!("fatal: {}", e); std::process::exit(1); } } ``` -------------------------------- ### Monitor::all Source: https://context7.com/nashaofu/xcap/llms.txt Enumerates all connected displays and returns a vector of Monitor objects. Each Monitor provides access to its properties like ID, name, position, size, and status. ```APIDOC ## Monitor::all ### Description Returns a `Vec` describing every connected display. Each `Monitor` is `Debug + Clone` and exposes lazy accessor methods for its properties. The list includes both primary and secondary screens. ### Method `Monitor::all()` ### Parameters None ### Response - **Vec** - A vector containing `Monitor` objects for each connected display. ### Request Example ```rust use xcap::Monitor; fn main() { let monitors = Monitor::all().expect("failed to enumerate monitors"); for monitor in &monitors { println!( "id={} name={:?} friendly={:?} pos=({}, {}) size={}x{} \n rotation={} scale={} freq={} Hz primary={} builtin={}", monitor.id().unwrap(), monitor.name().unwrap(), monitor.friendly_name().unwrap(), monitor.x().unwrap(), monitor.y().unwrap(), monitor.width().unwrap(), monitor.height().unwrap(), monitor.rotation().unwrap(), // 0 | 90 | 180 | 270 degrees monitor.scale_factor().unwrap(), // e.g. 2.0 on HiDPI / Retina monitor.frequency().unwrap(), // e.g. 60.0 or 120.0 monitor.is_primary().unwrap(), monitor.is_builtin().unwrap(), ); } } ``` ### Response Example ``` // Example output (macOS 14" MacBook Pro): id=1 name="Built-in Retina Display" friendly="Built-in Retina Display" pos=(0, 0) size=3456x2234 rotation=0 scale=2 freq=120 Hz primary=true builtin=true ``` ``` -------------------------------- ### Window::capture_image Source: https://context7.com/nashaofu/xcap/llms.txt Captures a screenshot of a specified window. This method will fail for minimized windows. ```APIDOC ## `Window::capture_image` — Capture a Single Window Takes a screenshot of the specified window regardless of its position on screen. Minimized windows cannot be captured; check `is_minimized()` first. ```rust use xcap::Window; fn sanitize(s: &str) -> String { s.replace(['|', '\\', ':', '/', '"'], "") } fn main() { std::fs::create_dir_all("target/windows").unwrap(); let windows = Window::all().unwrap(); let mut saved = 0usize; for (i, window) in windows.iter().enumerate() { if window.is_minimized().unwrap_or(true) { continue; // skip — minimized windows cannot be captured } match window.capture_image() { Ok(img) => { let path = format!( "target/windows/window-{}-{}.png", i, sanitize(&window.title().unwrap_or_default()) ); img.save(&path).unwrap(); println!("saved {} ({}x{})", path, img.width(), img.height()); saved += 1; } Err(e) => eprintln!("skipping window {}: {}", i, e), } } println!("captured {} window(s)", saved); } ``` ``` -------------------------------- ### Add XCap to Cargo.toml Source: https://context7.com/nashaofu/xcap/llms.txt Specifies the XCap dependency in Cargo.toml. The 'wgc' feature flag enables hardware-accelerated capture on Windows. ```toml [dependencies] xcap = "0.9.4" # Enable Windows Graphics Capture (Windows only; no effect on other platforms): # xcap = { version = "0.9.4", features = ["wgc"] } ``` -------------------------------- ### Save Raw Video Frame to Image Source: https://context7.com/nashaofu/xcap/llms.txt Converts a raw RGBA frame buffer to an RgbaImage and saves it to a file. Ensure the buffer size matches the frame dimensions. ```rust use xcap::{Monitor, Frame, image::RgbaImage}; use std::{thread, time::Duration}; fn save_frame(frame: Frame, path: &str) { let img = RgbaImage::from_raw(frame.width, frame.height, frame.raw) .expect("buffer size mismatch"); img.save(path).expect("failed to save frame"); println!( "frame saved to {} ({}x{}, {} bytes per frame)", path, img.width(), img.height(), img.width() * img.height() * 4 ); } fn main() { std::fs::create_dir_all("target").unwrap(); let monitor = Monitor::from_point(0, 0).unwrap(); let (recorder, rx) = monitor.video_recorder().unwrap(); recorder.start().unwrap(); // Block until the first frame arrives, then save and stop. if let Ok(frame) = rx.recv_timeout(Duration::from_secs(5)) { save_frame(frame, "target/single_frame.png"); } else { eprintln!("timed out waiting for frame"); } recorder.stop().unwrap(); // Output: frame saved to target/single_frame.png (3456x2234, 30930984 bytes per frame) } ``` -------------------------------- ### Capture Primary Monitor Region Source: https://github.com/nashaofu/xcap/blob/master/README.md Captures a specific rectangular region from the primary monitor. Calculates the center coordinates for the specified region dimensions. Requires the 'fs_extra' crate for directory creation. ```rust use fs_extra::dir; use std::time::Instant; use xcap::Monitor; fn normalized(filename: String) -> String { filename.replace(['|', '\\', ':', '/'], "") } fn main() -> Result<(), Box> { let monitors = Monitor::all()?; dir::create_all("target/monitors", true).unwrap(); let monitor = monitors .into_iter() .find(|m| m.is_primary().unwrap_or(false)) .expect("No primary monitor found"); let monitor_width = monitor.width()?; let monitor_height = monitor.height()?; let region_width = 400u32; let region_height = 300u32; let x = ((monitor_width as i32) - (region_width as i32)) / 2; let y = ((monitor_height as i32) - (region_height as i32)) / 2; let start = Instant::now(); let image = monitor.capture_region(x, y, region_width, region_height)?; println!( "Time to record region of size {}x{}: {:?}", image.width(), image.height(), start.elapsed() ); image .save(format!( "target/monitors/monitor-{}-region.png", normalized(monitor.friendly_name().unwrap()) )) .unwrap(); Ok(()) } ``` -------------------------------- ### Monitor::capture_image Source: https://context7.com/nashaofu/xcap/llms.txt Captures a full-screen screenshot of the specified monitor and returns it as an `image::RgbaImage`. The image dimensions correspond to the monitor's reported pixel width and height. ```APIDOC ## Monitor::capture_image ### Description Captures a full screenshot of the monitor and returns an `image::RgbaImage`. The image dimensions match the monitor's reported pixel width and height. The returned `RgbaImage` is compatible with every codec in the `image` crate. ### Method `monitor.capture_image()` ### Parameters This method is called on a `Monitor` object. ### Response - **image::RgbaImage** - An RGBA image representing the screenshot. ### Request Example ```rust use std::time::Instant; use xcap::Monitor; fn sanitize(name: String) -> String { name.replace(['|', '\\', ':', '/', '"'], "") } fn main() { std::fs::create_dir_all("target/monitors").unwrap(); let start = Instant::now(); for monitor in Monitor::all().unwrap() { let img = monitor.capture_image().expect("capture failed"); let path = format!( "target/monitors/monitor-{}.png", sanitize(monitor.friendly_name().unwrap()) ); img.save(&path).unwrap(); println!("saved {} ({}x{}) in {:?}", path, img.width(), img.height(), start.elapsed()); } } ``` ### Response Example ``` // Output: saved target/monitors/monitor-Built-in Retina Display.png (3456x2234) in 45ms ``` ``` -------------------------------- ### XCapError / XCapResult — Unified Error Handling Source: https://context7.com/nashaofu/xcap/llms.txt Explains the error handling mechanism in XCap, detailing common error variants and how to manage them. ```APIDOC ## `XCapError` / `XCapResult` — Unified Error Handling All fallible XCap functions return `XCapResult`, which is `Result`. The most commonly matched variants are `XCapError::NotSupported`, `XCapError::Error(String)`, and `XCapError::InvalidCaptureRegion(String)`. Platform-specific variants (e.g., `XcbError` on Linux, `WindowsCoreError` on Windows) are transparent wrappers that implement `std::error::Error`. ```rust use xcap::{Monitor, XCapError}; fn capture_primary() -> Result<(), XCapError> { let monitor = Monitor::all()? .into_iter() .find(|m| m.is_primary().unwrap_or(false)) .ok_or_else(|| XCapError::new("no primary monitor found"))?; // Attempt to capture an obviously out-of-bounds region. let result = monitor.capture_region(0, 0, u32::MAX, u32::MAX); match result { Ok(_) => println!("capture succeeded (unexpected)"), Err(XCapError::InvalidCaptureRegion(msg)) => { println!("region out of bounds: {}", msg); } Err(XCapError::NotSupported) => { println!("operation not supported on this platform"); } Err(e) => { println!("other error: {}", e); return Err(e); } } Ok(()) } fn main() { if let Err(e) = capture_primary() { eprintln!("fatal: {}", e); std::process::exit(1); } } ``` ``` -------------------------------- ### Find Display Under a Screen Coordinate with Monitor::from_point Source: https://context7.com/nashaofu/xcap/llms.txt Identifies the monitor that contains a given global screen coordinate (x, y). This is useful for determining which display a point, such as a mouse cursor, is currently on. ```rust use xcap::Monitor; fn main() { // Retrieve the monitor that contains the point (100, 100) in global screen space. let monitor = Monitor::from_point(100, 100) .expect("no monitor contains (100, 100)"); println!( "Point (100, 100) is on {:?} (primary: {})", monitor.friendly_name().unwrap(), monitor.is_primary().unwrap(), ); } ``` -------------------------------- ### Monitor::from_point Source: https://context7.com/nashaofu/xcap/llms.txt Finds the display that contains a given screen coordinate. This is useful for determining which monitor a specific point (like a mouse cursor) is located on. ```APIDOC ## Monitor::from_point ### Description Returns the `Monitor` that contains the given global screen coordinate `(x, y)`. Useful when you already know a pixel position (e.g., a mouse cursor location) and need the enclosing display. ### Method `Monitor::from_point(x: i32, y: i32)` ### Parameters #### Path Parameters - **x** (i32) - Required - The x-coordinate of the point. - **y** (i32) - Required - The y-coordinate of the point. ### Response - **Monitor** - The `Monitor` object that contains the specified point. ### Request Example ```rust use xcap::Monitor; fn main() { // Retrieve the monitor that contains the point (100, 100) in global screen space. let monitor = Monitor::from_point(100, 100) .expect("no monitor contains (100, 100)"); println!( "Point (100, 100) is on {:?} (primary:стен)", monitor.friendly_name().unwrap(), monitor.is_primary().unwrap(), ); } ``` ``` -------------------------------- ### Capture Specific Region of Monitor Source: https://context7.com/nashaofu/xcap/llms.txt Captures a rectangular sub-region of the monitor. Returns an error if the region extends beyond monitor bounds. Requires `xcap::Monitor`. ```rust use xcap::Monitor; fn main() -> Result<(), Box> { std::fs::create_dir_all("target/monitors").unwrap(); let monitor = Monitor::all()? .into_iter() .find(|m| m.is_primary().unwrap_or(false)) .expect("no primary monitor"); let mon_w = monitor.width()?; let mon_h = monitor.height()?; // Capture the centre 800×600 region. let region_w = 800u32; let region_h = 600u32; let x = ((mon_w as i32 - region_w as i32) / 2) as u32; let y = ((mon_h as i32 - region_h as i32) / 2) as u32; let img = monitor.capture_region(x, y, region_w, region_h)?; println!("captured region: {}x{}", img.width(), img.height()); img.save("target/monitors/centre-region.png")?; // Out-of-bounds example — results in XCapError::InvalidCaptureRegion: let bad = monitor.capture_region(mon_w / 2, mon_h / 2, mon_w, mon_h); assert!(matches!(bad, Err(xcap::XCapError::InvalidCaptureRegion(_)))); Ok(()) } ``` -------------------------------- ### Monitor::capture_region Source: https://context7.com/nashaofu/xcap/llms.txt Captures a rectangular sub-region of the monitor. Returns an error if the region extends beyond the monitor's bounds. ```APIDOC ## Monitor::capture_region ### Description Captures a rectangular sub-region of the monitor starting at pixel offset `(x, y)` with the given `width` and `height`. Returns `XCapError::InvalidCaptureRegion` if the rectangle extends beyond the monitor's bounds. ### Parameters - **x** (u32) - The x-coordinate of the top-left corner of the region. - **y** (u32) - The y-coordinate of the top-left corner of the region. - **width** (u32) - The width of the region to capture. - **height** (u32) - The height of the region to capture. ### Returns - `Result` - An `Image` object representing the captured region, or an `XCapError` if the region is invalid. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.