首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >tauri学习(6)-系统托盘systemTray

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

作者头像
菩提树下的杨过
发布2022-08-23 16:06:43
1.1K0
发布2022-08-23 16:06:43
举报

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

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

二、Rust中添加托盘

运行效果:

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

三、给托盘加菜单

效果:

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

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

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2022-08-21,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档