Search code examples
rustcolorswindowpixel

How to get pixel color under cursor?


I am looking for a way to get the pixel color value under the cursor.

This of course working from any window, not just a 'rust-owned' window like a winit window.

I found a few library of window capture and solution in other language , but nothing that fullfil my need.


Solution

  • Here is a simple cross-platform solution using autopilot.

    First get the cursor position using mouse::location() and then use that position to grab the pixel on the screen using screen::get_color(position).

    A full sample:

    fn main() {
        let mouse_location = autopilot::mouse::location();
        let pixel = autopilot::screen::get_color(mouse_location).unwrap();
        println!(
            "Pixel color under cursor (RGBA): {},{},{},{}",
            pixel.0[0], pixel.0[1], pixel.0[2], pixel.0[3]
        )
    }