Last active
November 27, 2024 10:47
-
-
Save Sovenok-Hacker/be081a8d1f7e8538262cfa5dcfafcedb to your computer and use it in GitHub Desktop.
Change Windows wallpaper using Rust and WinAPI (with BMP conversation included)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Cargo.toml packages | |
| windows = { version = "0.56.0", features = ["Win32_UI_WindowsAndMessaging"] } | |
| image = "0.25.1" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Example | |
| #[cfg(windows)] | |
| mod wallpaper; | |
| fn main() { | |
| wallpaper::to_bmp( | |
| "C:\\Users\\artem\\Desktop\\wp.jpg", # from file | |
| "C:\\Users\\artem\\Desktop\\wp.bmp", # to file | |
| ) | |
| .unwrap(); | |
| wallpaper::set_wallpaper("C:\\Users\\artem\\Desktop\\wp.bmp".to_string()).unwrap(); // set wallpaper using WinAPI | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| use anyhow::{Context, Result}; | |
| use core::ffi::c_void; | |
| use image::io::Reader as ImageReader; | |
| use windows::Win32::UI::WindowsAndMessaging::{ | |
| SystemParametersInfoA, SPIF_SENDWININICHANGE, SPIF_UPDATEINIFILE, SPI_SETDESKWALLPAPER, | |
| }; | |
| pub fn set_wallpaper(path: String) -> Result<()> { | |
| unsafe { | |
| SystemParametersInfoA( | |
| SPI_SETDESKWALLPAPER, | |
| 0, | |
| Some(path.clone().as_bytes_mut().as_mut_ptr() as *mut c_void), | |
| SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE, | |
| ) | |
| .context("Error calling SystemParametersInfoA")?; | |
| } | |
| Ok(()) | |
| } | |
| pub fn to_bmp(img_path: &str, out_path: &str) -> Result<()> { | |
| ImageReader::open(img_path)?.decode()?.save(&out_path)?; | |
| Ok(()) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment