core-foundation-rs
core-foundation-rs copied to clipboard
Question about how to list all running window app names [Code Review/Question]
I'm working with Rust and Core Foundations and I'd like to know if the code looks right or if it has some flaws or if I can make it simpler
use core_foundation::base::{FromVoid, TCFType, TCFTypeRef, ToVoid};
use core_foundation::dictionary::{CFDictionary, CFDictionaryRef};
use core_foundation::string::CFString;
use core_graphics::window::{copy_window_info, kCGNullWindowID, kCGWindowListOptionAll};
fn main() {
let windows_info = copy_window_info(kCGWindowListOptionAll, kCGNullWindowID).unwrap();
for window_info in windows_info.get_all_values() {
let key = CFString::from_static_string("kCGWindowName");
let winfo_hash: CFDictionary =
unsafe { TCFType::wrap_under_get_rule(window_info as CFDictionaryRef) };
let window_name = winfo_hash.get(ToVoid::to_void(&key));
let window_name: String =
unsafe { CFString::from_void(window_name.as_void_ptr()).to_string() };
println!("{:?}", window_name);
}
}
Is that right? or do we have a "simpler" way of doing that? My goal is to take a screenshot of the window app if t matches some criteria
Thanks in advance.
It's simpler if I declare the Dict Key and Value so I don't need to mess with pointers, I am still not sure about the usage of get_all_values
and TCFType::wrap_under_get_rule
#[warn(unused_imports)]
use core_foundation::base::{CFType, TCFType};
use core_foundation::dictionary::{CFDictionary, CFDictionaryRef};
use core_foundation::string::CFString;
use core_graphics::window::{copy_window_info, kCGNullWindowID, kCGWindowListOptionAll};
fn main() {
let windows_info = copy_window_info(kCGWindowListOptionAll, kCGNullWindowID).unwrap();
for window_info in windows_info.get_all_values() {
let key = CFString::from_static_string("kCGWindowName");
let winfo_hash: CFDictionary<CFString, CFType> =
unsafe { TCFType::wrap_under_get_rule(window_info as CFDictionaryRef) };
let window_name = winfo_hash
.get(key)
.downcast::<CFString>()
.unwrap()
.to_string();
println!("{:?}", window_name)
}
}