rust 如何正确地将App handler传递给Tauri中的其他模块?

zed5wv10  于 2024-01-08  发布在  其他
关注(0)|答案(1)|浏览(155)

问题

在Tauri应用程序中,我在main.rs中有这个main函数,我试图将应用程序句柄传递给system_tray.rs::get_system_tray函数。
我不明白你怎么能正确地传递应用程序句柄
我得到这个错误:

mismatched types
expected struct `tauri::SystemTray`
  found fn item `for<'a> fn(&'a tauri::AppHandle) -> tauri::SystemTray {system_tray::get_system_tray}`

字符串
在下面这行代码中:

.system_tray(system_tray::get_system_tray)

代码

main.rs

fn main() {
    tauri::Builder::default()
        .setup(setup_handler)
        .plugin(tauri_plugin_store::Builder::default().build())
        .system_tray(system_tray::get_system_tray)
        .on_system_tray_event(system_tray::on_system_tray_event)
        .invoke_handler(tauri::generate_handler![
            system_info::get_system_stats,
            cpu_info::get_cpu_stats
        ])
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}

系统托盘.rs

use tauri::{AppHandle, CustomMenuItem, Manager, SystemTray, SystemTrayEvent, SystemTrayMenu, SystemTrayMenuItem};

pub fn get_system_tray(app: &AppHandle) -> SystemTray {
    let app_version = app.package_info().version.to_string();
    let title_text = format!("Sigma File Manager Next {}", app_version);
    let title = CustomMenuItem::new("title".to_string(), title_text).disabled();
    let show_main_window = CustomMenuItem::new("show_main_window".to_string(), "Open app window");
    let reload_main_window = CustomMenuItem::new("reload_main_window".to_string(), "Reload app window");
    let quit = CustomMenuItem::new("quit".to_string(), "Quit");
    let tray_menu = SystemTrayMenu::new()
        .add_item(title)
        .add_native_item(SystemTrayMenuItem::Separator)
        .add_item(show_main_window)
        .add_item(reload_main_window)
        .add_native_item(SystemTrayMenuItem::Separator)
        .add_item(quit);

    SystemTray::new().with_menu(tray_menu)
}

bvjveswy

bvjveswy1#

如果你需要一个AppHandle来生成SystemTray,你应该可以在运行时build托盘,如下所示:

fn main() {
    tauri::Builder::default()
        .invoke_handler(tauri::generate_handler![greet])
        .setup(|app| {
            let handle = app.handle();

            let _tray_handle = system_tray::get_system_tray(&handle).build(app)?;

            Ok(())
        })
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}

字符串
这也将允许您在需要时更新托盘。

相关问题