tauri学习(6)-系统托盘systemTray

2022-08-23 16:06:43 浏览数 (1)

接上节继续,研究下系统托盘。

一、tauri.conf.json配置启用系统托盘

二、Rust中添加托盘

运行效果:

但是只有一个托盘图标,点了啥反应都没有。

三、给托盘加菜单

效果:

接下来,给托盘及托盘菜单添加事件响应:

代码语言:javascript复制
use tauri::{
  CustomMenuItem, Manager, SystemTray, SystemTrayEvent, SystemTrayMenu, SystemTrayMenuItem,
};

fn main() {
  let quit = CustomMenuItem::new("quit".to_string(), "关闭窗口");
  let hide = CustomMenuItem::new("hide".to_string(), "隐藏窗口");
  let tray_menu = SystemTrayMenu::new()
    .add_item(quit)
    .add_native_item(SystemTrayMenuItem::Separator)
    .add_item(hide);

  let system_tray = SystemTray::new().with_menu(tray_menu);

  tauri::Builder::default()
    .system_tray(system_tray)
    .on_system_tray_event(|app, event| menu_handle(app, event))
    .run(tauri::generate_context!())
    .expect("failed to run app");
}

fn menu_handle(app_handle: &tauri::AppHandle, event: SystemTrayEvent) {
  match event {
    SystemTrayEvent::LeftClick {
      position: _,
      size: _,
      ..
    } => {
      println!("鼠标-左击");
    }
    SystemTrayEvent::RightClick {
      position: _,
      size: _,
      ..
    } => {
      println!("鼠标-右击");
    }
    SystemTrayEvent::DoubleClick {
      position: _,
      size: _,
      ..
    } => {
      println!("鼠标-双击");
    }
    SystemTrayEvent::MenuItemClick { id, .. } => match id.as_str() {
      "quit" => {
        std::process::exit(0);
      }
      "hide" => {
        let item_handle = app_handle.tray_handle().get_item(&id);
        let window = app_handle.get_window("home").unwrap();
        if window.is_visible().unwrap() {
          window.hide().unwrap();
          item_handle.set_title("显示窗口").unwrap();
        } else {
          window.show().unwrap();
          item_handle.set_title("隐藏窗口").unwrap();
        }
      }
      _ => {}
    },
    _ => {}
  }
}

核心都在menu_handle函数中

参考文章:

https://tauri.app/v1/guides/features/system-tray

0 人点赞