rust Tauri切换应用程序在任务栏图标上的可见性

xvw2m8pv  于 2022-11-12  发布在  其他
关注(0)|答案(1)|浏览(301)

我正在创建一个小应用程序,我想作为一个“托盘应用程序”。我的意思是,我不想显示一个停靠图标,只有一个托盘图标。
我希望应用程序窗口在首次打开时可见。
那么当用户通过点击窗口的X按钮关闭应用程序时,应用程序应该关闭(最小化)。如果用户左键点击托盘图标,也应该发生同样的情况。
如果应用程序已最小化,单击任务栏图标应再次显示应用程序窗口。
我希望任务栏菜单只有在用户右键单击任务栏图标时才可见。

简言之:

  • 按一下系统匣图标:切换应用程序可见性(不显示菜单)
  • 右键单击任务栏图标:显示“应用任务栏上下文菜单”(不切换应用的可见性)

这是我第一次使用金牛座和使用铁 rust ,所以我有点迷路了。
通过搜索和尝试不同的东西,我来到这个(在我的src-tauri/src/main.rs文件):


# ![cfg_attr(

    all(not(debug_assertions), target_os = "windows"),
    windows_subsystem = "windows"
)]

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

fn main() {
    let quit = CustomMenuItem::new("quit".to_string(), "Quit");
    let hide = CustomMenuItem::new("hide".to_string(), "Hide");

    let tray_menu = SystemTrayMenu::new()
        .add_item(quit)
        .add_native_item(SystemTrayMenuItem::Separator)
        .add_item(hide);
    let tray = SystemTray::new().with_menu(tray_menu);

    tauri::Builder::default()
        .on_system_tray_event(|app, event| match event {
            SystemTrayEvent::LeftClick { .. } => {
                let window = match app.get_window("main") {
                    Some(window) => match window.is_visible().expect("winvis") {
                        true => {
                            // hide the window instead of closing due to processes not closing memory leak: https://github.com/tauri-apps/wry/issues/590
                            window.hide().expect("winhide");
                            // window.close().expect("winclose");
                            return;

                        }
                        false => window,
                    },
                    None => return,
                };
                #[cfg(not(target_os = "macos"))]
                {
                    window.show().unwrap();
                }
                window.set_focus().unwrap();
            }
            _ => {}
        })
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}

这会在单击鼠标左键时切换应用程序的可见性,但同时也会显示“上下文菜单”。
关于如何实现我所寻找的目标有什么想法吗?

j2cgzkjk

j2cgzkjk1#

这会在单击鼠标左键时切换应用程序的可见性,但同时也会显示“上下文菜单”。
您可以在tauri.conf.json文件中进行配置(适用于macOS):https://tauri.app/v1/api/config/#systemtrayconfig.menuonleftclick它看起来像这样

{
  "tauri": {
    "systemTray": {
      "iconPath": "icons/icon.png",
      "menoOnLeftClick": false
    }
  }
}

关于其他平台的更多信息:

  • 这是Windows上的默认(也是唯一)行为。
  • 这在Linux上是不可能的,因为libappindicator的限制(设计决定)(这就是为什么在Linux上不发出LeftClick事件)。因此,如果你也想支持Linux,你可能不得不求助于基于菜单的替代方案。

相关问题