Tauri之单例+多窗口

Tauri之单例+多窗口

Tauri 1.4 + React 18

单例可以通过tauri_plugin_single_instance实现,多窗口可以简单通过路由来实现

单例

    tauri::Builder::default()
        .setup(|app| {
            let mut label = "home";
            let args: Vec<String> = std::env::args().collect();
            if args.len() > 1 {
                label = args.get(1).unwrap();
            }
            let mut runtime: tokio::runtime::Runtime = tokio::runtime::Runtime::new().expect("Unable to create a runtime");
            let s = runtime.block_on(create_window(label, &app.handle()));
            Ok(())
        })
        .plugin(tauri_plugin_single_instance::init(|app, argv, cwd| {
            let mut label = "home";
            if argv.len() > 1 {
                label = argv.get(1).unwrap();
            }
            let mut runtime = tokio::runtime::Runtime::new().expect("Unable to create a runtime");
            let s = runtime.block_on(create_window(label, app));
        }))
  • 创建窗口的操作要异步,否则可能会卡死
  • setup时创建初始化窗口
  • tauri_plugin_single_instance处理重复打开操作

多窗口

async fn create_window(label: &str, app: &tauri::AppHandle) {
    let config = get_window_config(label);
    if let Some(window) = app.get_window(label) {
        let _ = window.show();
        let _ = window.set_focus();
        let _ = window.request_user_attention(Some(UserAttentionType::Informational));
    } else {
        let window = tauri::window::WindowBuilder::new(
            app,
            label,
            tauri::WindowUrl::App(label.parse().unwrap()),
        )
        .center()
        .title(config["title"].as_str().unwrap())
        .inner_size(config["width"].as_f64().unwrap(), config["height"].as_f64().unwrap())
        .build()
        .unwrap();
        window.set_focus();
    }
}
    
      
      } />
        } />
        } />
      
    
  • 通过唯一label区分窗口,动态创建新窗口或恢复旧窗口

  • 动态创建窗口的时候,记得清空tauri.config.json里的windows

      "tauri": {
        "windows": [
        ]
      }
    
  • 这里前端部分使用react 18 + react-router-dom 6,注意要使用BrowserRouter

你可能感兴趣的:(Tauri,tauri,rust,react,单例,多窗口)