Rust 根据窗口类判断窗口是否被激活

180it 2024-10-09 PM 73℃ 0条
extern crate winapi;
use std::ffi::CString;
use std::ptr::null_mut;
use winapi::um::winuser::{FindWindowA, GetForegroundWindow};
use winapi::shared::windef::HWND;

fn find_window_by_class(class_name: &str) -> Option<HWND> {
    let c_class_name = CString::new(class_name).expect("CString::new failed");
    let hwnd = unsafe { FindWindowA(c_class_name.as_ptr(), null_mut()) };
    if hwnd.is_null() {
        None
    } else {
        Some(hwnd)
    }
}

fn is_window_active(hwnd: HWND) -> bool {
    let foreground_hwnd = unsafe { GetForegroundWindow() };
    hwnd == foreground_hwnd
}

fn main() {

loop{
    let class_name = "WeChatMainWndForPC";
    match find_window_by_class(class_name) {
        Some(hwnd) => {
            println!("Found window with handle: {:?}", hwnd);
            if is_window_active(hwnd) {
                println!("The window with class name '{}' is active.", class_name);
            } else {
                println!("The window with class name '{}' is not active.", class_name);
            }
        }
        None => println!("Window with class name '{}' not found", class_name),
    }
    
    
    
use std::thread::sleep;
use std::time::Duration;
//std::thread::sleep(Duration::from_millis(1000);
std::thread::sleep(Duration::from_secs(1));

    }
}



[dependencies]
winapi = { version = "0.3", features = ["winuser"] }
支付宝打赏支付宝打赏 微信打赏微信打赏

如果文章或资源对您有帮助,欢迎打赏作者。一路走来,感谢有您!

标签: none

Rust 根据窗口类判断窗口是否被激活