要想实现记住窗口大小的功能,整体逻辑就是要监听窗口大小变化,将窗口大小保存下来,重启之后,读取保存的大小,然后恢复。这里可以使用rust层实现,也可以在前端实现。我这里就纯rust层实现了。
监听窗口变化
使用tauri-plugin-store这个插件,插件地址:plugins-workspace/plugins/store at v2 · tauri-apps/plugins-workspace · GitHub,
安装插件:
然后导入插件:
开始监听窗口变化逻辑:
逻辑代码:
.setup(|app| {
let window = app.get_webview_window("main").unwrap();
// This loads the store from disk
let store = app.store("app_data.json")?;
let window_size: Option<serde_json::Value> = store.get("window_size");
println!("windows_size: {:?}", window_size);
if let Some(window_size) = window_size {
let size = window_size.as_object().unwrap();
let width = size["width"].as_f64().unwrap();
let height = size["height"].as_f64().unwrap();
window
.set_size(tauri::PhysicalSize::new(width, height))
.unwrap();
}
// 监听窗口大小变化
window.on_window_event(move |event| {
if let WindowEvent::Resized(size) = event {
println!("window_size: {:?}", size);
let _ = store.set(
"window_size",
json!({
"width": size.width,
"height": size.height
}),
);
}
});
Ok(())
})
.run(tauri::generate_context!())
然后启动软件,重新调整大小,再次启动,就可以看到效果了: