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

2022/8/22 6:56:57

本文主要是介绍tauri学习(6)-系统托盘systemTray,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

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

一、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



这篇关于tauri学习(6)-系统托盘systemTray的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程