Skip to content

Instantly share code, notes, and snippets.

@Vurv78
Last active February 28, 2021 05:40
Show Gist options
  • Save Vurv78/7983ba9c12bcf9f5bbe3e98e73a5c048 to your computer and use it in GitHub Desktop.
Save Vurv78/7983ba9c12bcf9f5bbe3e98e73a5c048 to your computer and use it in GitHub Desktop.
getOpenWindows function
// Requires winapi-rs.
// Accidentally made this instead of a getOpenPrograms function so just putting it as a gist so it doesn't go to waste.
use winapi::{
um::winuser::{EnumWindows, GetWindowTextW}
};
static mut windows: Vec<String> = Vec::new(); // Use a static because local variables aren't sent to non-closure functions.
unsafe fn getOpenWindows() -> bool {
const MAXSIZE: usize = 100; // Maximum size of window title.
windows = Vec::new();
unsafe extern "system" fn windowCallback(wnd: HWND, lparam: isize) -> BOOL {
let mut name_buf: [u16; MAXSIZE] = [0; MAXSIZE]; // Fetch the name from windows into a utf16 array
GetWindowTextW(wnd, name_buf.as_mut_ptr(), MAXSIZE as i32);
if let Ok(name) = String::from_utf16(&name_buf) {
windows.push(name);
}
return 1;
}
EnumWindows(Some(windowCallback), 0)!=0
}
fn main() {
unsafe{
println!("Success. {}, ", getOpenWindows());
println!("Windows: {:?}", windows);
}
}
@Vurv78
Copy link
Author

Vurv78 commented Feb 28, 2021

Don't think the return value is whether it errored in getting a window title, rather if you prematurely exit by returning 0 / C TRUE inside windowCallback.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment