墨香阁
| 分享生活的点滴

tauri版本2的系统托盘

2024年10月07日 07:39:17
12 views
2 min read
前端
tauri版本2的系统托盘

Tauri 2.0.0-rc 系统托盘实现指南

在 Tauri 2.0.0-rc 版本中,你有两种主要方式来实现系统托盘功能。以下是这两种方式的详细说明和代码示例。

方式一:通过 tauri.conf.json 配置

tauri.conf.json 文件中,你可以直接配置系统托盘的属性,如图标路径、标题和提示信息。

  • 第一中是
json
{ "tauri": { "app": { "windows": [ { "title": "time", "width": 800, "height": 600 } ], "security": { "csp": null }, "trayIcon": { "iconPath": "icons/icon.ico", "iconAsTemplate": true, "title": "时间管理器", "tooltip": "时间管理器" } } } }

这种方式简单直接,适用于不需要复杂交互的托盘图标。

方式二:通过 Rust 代码创建

如果你需要更复杂的交互,比如点击托盘图标显示菜单或执行特定操作,你可以通过 Rust 代码来创建系统托盘。

1. 创建托盘菜单

首先,你需要定义托盘菜单项和子菜单。

tray.rs

rs
use tauri::{ menu::{Menu, MenuItem, Submenu}, tray::{MouseButton, MouseButtonState, TrayIconBuilder, TrayIconEvent}, Manager, Runtime, }; pub fn create_tray<R: Runtime>(app: &tauri::AppHandle<R>) -> tauri::Result<()> { let quit_i = MenuItem::with_id(app, "quit", "突出", true, None::<&str>)?; let show_i = MenuItem::with_id(app, "show", "显示", true, None::<&str>)?; let hide_i = MenuItem::with_id(app, "hide", "隐藏", true, None::<&str>)?; let edit_i = MenuItem::with_id(app, "edit_file", "编辑", true, None::<&str>)?; let new_i = MenuItem::with_id(app, "new_file", "添加", true, None::<&str>)?; let a =Submenu::with_id_and_items(app, "File", "文章", true, &[&new_i, &edit_i])?; // 分割线 let menu = Menu::with_items(app, &[&quit_i, &show_i, &hide_i, &a])?; let _ = TrayIconBuilder::with_id("tray") .icon(app.default_window_icon().unwrap().clone()) .menu(&menu) .menu_on_left_click(false) .on_menu_event(move |app, event| match event.id.as_ref() { "quit" => { app.exit(0); }, "show" => { let window = app.get_webview_window("main").unwrap(); let _ = window.show(); }, "hide" => { let window = app.get_webview_window("main").unwrap(); let _ = window.hide(); }, "edit_file" => { println!("edit_file"); }, "new_file" => { println!("new_file"); }, // Add more events here _ => {} }) .on_tray_icon_event(|tray, event| { if let TrayIconEvent::Click { button: MouseButton::Left, button_state: MouseButtonState::Up, .. } = event { let app = tray.app_handle(); if let Some(window) = app.get_webview_window("main") { let _ = window.show(); let _ = window.set_focus(); } } }) .build(app); Ok(()) }

2. 注册托盘创建函数

在你的主函数中,你需要注册 create_tray 函数,以便在应用启动时创建系统托盘

lib.rs

rs
#[cfg(desktop)] mod tray; pub fn run() { tauri::Builder::default() // ... .setup(|app| { #[cfg(all(desktop))] { let handle = app.handle(); tray::create_tray(handle)?; } Ok(()) }) // ... .run(tauri::generate_context!()) .expect("error while running tauri application"); }

总结

通过上述两种方式,你可以在 Tauri 2.0.0-rc 应用程序中实现系统托盘功能。第一种方式适用于简单的托盘图标显示,而第二种方式提供了更多的自定义和交互可能性。根据你的应用需求选择合适的实现方

  • 参考资料https://v2.tauri.app/zh-cn/plugin/system-tray/#creating-the-system-tray-in-rust

发表留言

全部留言 (0)

暂无留言,成为第一个留言的人吧!