Skip to content

Instantly share code, notes, and snippets.

@Sovenok-Hacker
Last active November 27, 2024 10:47
Show Gist options
  • Select an option

  • Save Sovenok-Hacker/be081a8d1f7e8538262cfa5dcfafcedb to your computer and use it in GitHub Desktop.

Select an option

Save Sovenok-Hacker/be081a8d1f7e8538262cfa5dcfafcedb to your computer and use it in GitHub Desktop.
Change Windows wallpaper using Rust and WinAPI (with BMP conversation included)
# Cargo.toml packages
windows = { version = "0.56.0", features = ["Win32_UI_WindowsAndMessaging"] }
image = "0.25.1"
// 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
}
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