wallpaper_windows_user32/
lib.rs

1use std::path::{Path, PathBuf};
2
3use winapi::shared::minwindef::{MAX_PATH, TRUE, UINT};
4use winapi::um::winnt::{HRESULT, PVOID, WCHAR};
5use winapi::um::winuser::{
6    SystemParametersInfoW, SPIF_SENDCHANGE, SPIF_UPDATEINIFILE, SPI_GETDESKWALLPAPER,
7    SPI_SETDESKWALLPAPER,
8};
9
10use widestring::{U16CStr, U16CString};
11
12mod error;
13
14pub use error::Error;
15
16pub type Result<T> = std::result::Result<T, Error>;
17
18/// Set desktop image.
19///
20/// ```no_run
21/// use wallpaper_windows_user32::set;
22/// use std::path::{Path, PathBuf};
23///
24/// let path = Path::new(r#"C:\Users\User\AppData\Local\Temp\qwerty.jpg"#);
25/// let result = set(path);
26/// assert!(result.is_ok())
27/// ```
28pub fn set<T: AsRef<Path>>(full_path: T) -> Result<()> {
29    let full_path: U16CString = U16CString::from_os_str(full_path.as_ref())?;
30    let ret = unsafe {
31        SystemParametersInfoW(
32            SPI_SETDESKWALLPAPER,
33            0,
34            full_path.as_ptr() as PVOID,
35            SPIF_SENDCHANGE | SPIF_UPDATEINIFILE,
36        )
37    };
38    check_result(ret)?;
39    Ok(())
40}
41
42/// Get desktop image.
43///
44/// ```no_run
45/// use wallpaper_windows_user32::get;
46/// use std::path::{Path, PathBuf};
47///
48/// let wallpaper_path: PathBuf = get().unwrap();
49/// assert_eq!(Path::new(r#"C:\Users\User\AppData\Local\Temp\qwerty.jpg"#), wallpaper_path)
50/// ```
51pub fn get() -> Result<PathBuf> {
52    let mut full_path_buf = [0 as WCHAR; MAX_PATH];
53    let ret = unsafe {
54        SystemParametersInfoW(
55            SPI_GETDESKWALLPAPER,
56            full_path_buf.len() as UINT,
57            full_path_buf.as_mut_ptr() as PVOID,
58            0,
59        )
60    };
61    check_result(ret)?;
62    let full_path: &U16CStr = U16CStr::from_slice_with_nul(&full_path_buf)?;
63    Ok(full_path.to_os_string().into())
64}
65
66fn check_result(result: HRESULT) -> Result<()> {
67    match result {
68        TRUE => Ok(()),
69        _ => Err(std::io::Error::from_raw_os_error(result))?,
70    }
71}