How to get the rbg value of a pixel on screen

use windows::Win32::Graphics::Gdi::GetDC;
use windows::Win32::Graphics::Gdi::GetPixel;

fn main() {
    let x = 1332;
    //The x-coordinate, in logical units, of the pixel to be examined.
    let y = 500;
    //The y-coordinate, in logical units, of the pixel to be examined.
    unsafe {
        let hwnd = GetDC(None);

        let a = GetPixel(hwnd, x, y);
        let a_u32: u32 = a.0;
        println!("Pixel as hexadecimal 0x{:X}", a_u32);
        if a_u32 ==0x00FFFFFF {
            println!("The pixel at {} , {} is white", x, y);
        } else {
            println!("The pixel at {} , {} is not white", x, y);
        }
    }
}

Put this in cargo.toml

[dependencies]
windows = { version = "0.52", features = [
    "Win32_Foundation",
    "Win32_Graphics_Gdi",
   
] }

This code returns COLORREF value for a pixel. This can be converted into RGB.

I don't know how you are supposed to do this but I got this hacky solution by looking at github code for crates which take a screenshot and guessing.

2 Likes