tauri v2 中react怎么获取电脑长宽像素值

注意 react 是前端,只能获取浏览器长宽,就是软件页面的长宽,不能获取显示器硬件的长宽信息。

所以只能用 rust 方法获取。

Tauri v2 提供了 Monitor 结构体,可以直接获取主显示器或所有显示器的物理尺寸。这是最标准、最安全且跨平台(Windows/macOS/Linux)的做法。

rust 复制代码
#[tauri::command]
fn get_screen_size(app_handle: tauri::AppHandle) -> Result<(u32, u32), String> {
    // 获取主显示器
    if let Ok(Some(monitor)) = app_handle.primary_monitor() {
        // size() 返回的是 PhysicalSize,单位是物理像素
        let size = monitor.size();
        Ok((size.width, size.height))
    } else {
        Err("No primary monitor found".to_string())
    }
}
// 或者获取所有显示器的信息
#[tauri::command]
fn get_all_monitors(app_handle: tauri::AppHandle) -> Vec<(u32, u32)> {
    let monitors = app.available_monitors().map_err(|err| err.to_string())?;
    for (index, monitor) in monitors.into_iter().enumerate() {

    }
}

如果需要逻辑像素(考虑 DPI 缩放),可以使用 monitor.scale_factor() 进行计算:逻辑宽度 = 物理宽度 / scale_factor

Windows 平台专用(使用 winapi)

1. 添加依赖

src-tauri/Cargo.toml 中添加:

rust 复制代码
[target.'cfg(target_os = "windows")'.dependencies]
winapi = { version = "0.3", features = ["winuser"] }

2. Rust 代码实现

rust 复制代码
#[cfg(target_os = "windows")]
fn get_windows_screen_size() -> (u32, u32) {
    use winapi::um::winuser::{GetSystemMetrics, SM_CXSCREEN, SM_CYSCREEN};
    
    // SM_CXSCREEN: 屏幕宽度
    // SM_CYSCREEN: 屏幕高度
    let width = unsafe { GetSystemMetrics(SM_CXSCREEN) } as u32;
    let height = unsafe { GetSystemMetrics(SM_CYSCREEN) } as u32;
    
    (width, height)
}