🐛 修复程序最小化时托盘点击异常

This commit is contained in:
BTMuli
2025-12-24 20:23:15 +08:00
parent 972a9a5a99
commit 715b53ba82

View File

@@ -1,12 +1,23 @@
//! @file src/tray.rs
//! @desc 系统托盘模块,负责创建和管理系统托盘图标
//! @since Beta v0.8.8
// 系统托盘模块,负责创建和管理系统托盘图标
// @since Beta v0.9.1
use tauri::image::Image;
use tauri::menu::{MenuBuilder, MenuItemBuilder, PredefinedMenuItem};
use tauri::tray::{MouseButton, MouseButtonState, TrayIconBuilder, TrayIconEvent};
use tauri::{AppHandle, Manager, Runtime};
/// 显示主窗口(带最小化判断)
fn show_main_window<R: Runtime>(app: &AppHandle<R>) {
if let Some(window) = app.get_webview_window("TeyvatGuide") {
// 如果窗口处于最小化状态,则恢复
if let Ok(true) = window.is_minimized() {
let _ = window.unminimize();
}
let _ = window.show();
let _ = window.set_focus();
}
}
/// 创建系统托盘图标
pub fn create_tray<R: Runtime>(app: &AppHandle<R>) -> tauri::Result<()> {
// 创建托盘菜单
@@ -17,14 +28,7 @@ pub fn create_tray<R: Runtime>(app: &AppHandle<R>) -> tauri::Result<()> {
let menu = MenuBuilder::new(app).item(&show_item).item(&separator).item(&quit_item).build()?;
// 加载托盘图标
// 在不同操作系统上,托盘图标的显示效果可能有所不同:
// - Windows: 使用 .ico 格式获得最佳效果
// - macOS: 支持 .icns 和 .png 格式
// - Linux: 通常使用 .png 格式
let icon_bytes = include_bytes!("../icons/32x32.png");
// 使用 image crate 解码 PNG 图标
// Tauri 的 Image 结构只接受原始 RGBA 数据,因此需要使用 image crate 解码 PNG
let img = image::load_from_memory(icon_bytes).map_err(|e| {
tauri::Error::InvalidIcon(std::io::Error::new(std::io::ErrorKind::InvalidData, e))
})?;
@@ -37,26 +41,19 @@ pub fn create_tray<R: Runtime>(app: &AppHandle<R>) -> tauri::Result<()> {
.icon(icon)
.tooltip("Teyvat Guide")
.menu(&menu)
.on_menu_event(|app, event| {
match event.id.as_ref() {
"show" => {
if let Some(window) = app.get_webview_window("TeyvatGuide") {
let _ = window.show();
let _ = window.set_focus();
}
}
"quit" => {
// 关闭所有子窗口
for label in crate::SUB_WINDOW_LABELS.iter() {
if let Some(sub) = app.get_webview_window(label) {
let _ = sub.destroy();
}
}
// 退出应用
app.exit(0);
}
_ => {}
.on_menu_event(|app, event| match event.id.as_ref() {
"show" => {
show_main_window(app);
}
"quit" => {
for label in crate::SUB_WINDOW_LABELS.iter() {
if let Some(sub) = app.get_webview_window(label) {
let _ = sub.destroy();
}
}
app.exit(0);
}
_ => {}
})
.on_tray_icon_event(|tray, event| {
if let TrayIconEvent::Click {
@@ -66,10 +63,7 @@ pub fn create_tray<R: Runtime>(app: &AppHandle<R>) -> tauri::Result<()> {
} = event
{
let app = tray.app_handle();
if let Some(window) = app.get_webview_window("TeyvatGuide") {
let _ = window.show();
let _ = window.set_focus();
}
show_main_window(&app);
}
})
.build(app)?;