feat: prevent close on request

This commit is contained in:
椰子 2024-11-01 18:48:28 +08:00
parent 92418de6b6
commit 7ffecba549
2 changed files with 29 additions and 8 deletions

View File

@ -18,7 +18,7 @@ crate-type = ["staticlib", "cdylib", "rlib"]
tauri-build = { version = "2", features = [] } tauri-build = { version = "2", features = [] }
[dependencies] [dependencies]
tauri = { version = "2", features = ["tray-icon"] } tauri = { version = "2", features = ["unstable", "tray-icon"] }
tauri-plugin-shell = "2" tauri-plugin-shell = "2"
serde = { version = "1", features = ["derive"] } serde = { version = "1", features = ["derive"] }
serde_json = "1" serde_json = "1"

View File

@ -1,3 +1,9 @@
use tauri::{
menu::{Menu, MenuItem},
tray::{MouseButton, MouseButtonState, TrayIconBuilder, TrayIconEvent},
Manager,
};
// Learn more about Tauri commands at https://tauri.app/develop/calling-rust/ // Learn more about Tauri commands at https://tauri.app/develop/calling-rust/
#[tauri::command] #[tauri::command]
fn greet(name: &str) -> String { fn greet(name: &str) -> String {
@ -6,20 +12,28 @@ fn greet(name: &str) -> String {
#[cfg_attr(mobile, tauri::mobile_entry_point)] #[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() { pub fn run() {
use tauri::{
menu::{Menu, MenuItem},
tray::TrayIconBuilder,
};
tauri::Builder::default() tauri::Builder::default()
.setup(|app| { .setup(|app| {
let quit_i = MenuItem::with_id(app, "quit", "Quit", true, None::<&str>)?; let quit_i = MenuItem::with_id(app, "quit", "Quit", true, None::<&str>)?;
let menu = Menu::with_items(app, &[&quit_i])?; let menu = Menu::with_items(app, &[&quit_i])?;
let _tray: tauri::tray::TrayIcon = TrayIconBuilder::new() let _tray: tauri::tray::TrayIcon = TrayIconBuilder::new()
.tooltip("Realtime Voice Changer")
.icon(app.default_window_icon().unwrap().clone()) .icon(app.default_window_icon().unwrap().clone())
.on_tray_icon_event(|icon: &tauri::tray::TrayIcon, event| match event {
TrayIconEvent::Click {
button: MouseButton::Left,
button_state: MouseButtonState::Up,
..
} => {
icon.app_handle()
.get_window("main").unwrap()
.show().unwrap();
println!("Tray icon clicked");
}
_ => {}
})
.menu(&menu) .menu(&menu)
.menu_on_left_click(true) .menu_on_left_click(false)
.on_menu_event(|app, event| match event.id.as_ref() { .on_menu_event(|app, event| match event.id.as_ref() {
"quit" => { "quit" => {
println!("quit menu item was clicked"); println!("quit menu item was clicked");
@ -32,6 +46,13 @@ pub fn run() {
.build(app)?; .build(app)?;
Ok(()) Ok(())
}) })
.on_window_event(|window, event| match event {
tauri::WindowEvent::CloseRequested { api, .. } => {
window.hide().unwrap();
api.prevent_close();
}
_ => {}
})
.plugin(tauri_plugin_shell::init()) .plugin(tauri_plugin_shell::init())
.invoke_handler(tauri::generate_handler![greet]) .invoke_handler(tauri::generate_handler![greet])
.run(tauri::generate_context!()) .run(tauri::generate_context!())