You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Tauri托盘应用开发:左键切换窗口显隐、右键唤菜单

解决方案

问题根源是Tauri默认会为绑定了菜单的托盘图标触发左键弹出菜单的行为,只需在左键点击事件中阻止默认行为即可解决,同时补充右键菜单的点击逻辑让功能完整。

修改后的完整代码:

#![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 { event, .. } => {
                // 阻止系统默认的左键弹出菜单行为
                event.prevent_default();
                
                let window = match app.get_window("main") {
                    Some(window) => match window.is_visible().expect("winvis") {
                        true => {
                            window.hide().expect("winhide");
                            return;
                        }
                        false => window,
                    },
                    None => return,
                };
                #[cfg(not(target_os = "macos"))]
                {
                    window.show().unwrap();
                }
                window.set_focus().unwrap();
            }
            // 处理右键菜单的点击事件
            SystemTrayEvent::MenuItemClick { id, .. } => {
                let window = app.get_window("main").unwrap();
                match id.as_str() {
                    "quit" => app.exit(0),
                    "hide" => window.hide().expect("winhide"),
                    _ => {}
                }
            }
            _ => {}
        })
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}

关键修改说明:

  • 在LeftClick分支中添加event.prevent_default(),彻底阻止左键触发菜单的默认行为
  • 补充MenuItemClick事件处理,实现右键菜单的退出、隐藏窗口功能(原代码未处理菜单点击逻辑)

额外配置补充:

  1. 确保应用启动时窗口可见,在tauri.conf.json的窗口配置中设置:
"windows": [
  {
    "title": "你的应用名称",
    "width": 800,
    "height": 600,
    "visible": true
  }
]
  1. macOS下隐藏dock图标,在tauri.conf.json的bundle配置中添加:
"tauri": {
  "bundle": {
    "macOS": {
      "extendInfo": {
        "LSUIElement": true
      }
    }
  }
}

内容的提问来源于stack exchange,提问作者Boguz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 13:45:30