@@ -41,14 +41,28 @@ pub fn run() {
4141 Ok ( ( ) )
4242 } )
4343 . on_window_event ( |window, event| {
44- if let tauri:: WindowEvent :: CloseRequested { .. } = event {
45- if window. label ( ) == "main" {
46- stop_backend ( ) ;
44+ match event {
45+ tauri:: WindowEvent :: CloseRequested { .. } => {
46+ if window. label ( ) == "main" {
47+ stop_backend ( ) ;
48+ }
49+ }
50+ tauri:: WindowEvent :: Destroyed => {
51+ if window. label ( ) == "main" {
52+ stop_backend ( ) ;
53+ }
4754 }
55+ _ => { }
4856 }
4957 } )
50- . run ( tauri:: generate_context!( ) )
51- . expect ( "error while running tauri application" ) ;
58+ . build ( tauri:: generate_context!( ) )
59+ . expect ( "error while building tauri application" )
60+ . run ( |_app_handle, event| {
61+ // 应用退出时确保关闭后端
62+ if let tauri:: RunEvent :: Exit = event {
63+ stop_backend ( ) ;
64+ }
65+ } ) ;
5266}
5367
5468fn start_backend_sidecar ( app : & tauri:: AppHandle ) -> Result < ( ) , String > {
@@ -93,8 +107,33 @@ fn start_backend_sidecar(app: &tauri::AppHandle) -> Result<(), String> {
93107fn stop_backend ( ) {
94108 if let Ok ( mut guard) = BACKEND_HANDLE . lock ( ) {
95109 if let Some ( child) = guard. take ( ) {
96- let _ = child. kill ( ) ;
97- println ! ( "Backend process stopped" ) ;
110+ match child. kill ( ) {
111+ Ok ( _) => println ! ( "Backend process stopped successfully" ) ,
112+ Err ( e) => eprintln ! ( "Failed to stop backend: {}" , e) ,
113+ }
98114 }
99115 }
116+
117+ // 额外清理:尝试终止所有遗留的后端进程
118+ #[ cfg( windows) ]
119+ {
120+ let _ = std:: process:: Command :: new ( "taskkill" )
121+ . args ( [ "/F" , "/IM" , "loarchive-backend-x86_64-pc-windows-msvc.exe" ] )
122+ . creation_flags ( 0x08000000 ) // CREATE_NO_WINDOW
123+ . output ( ) ;
124+ }
125+ }
126+
127+ // Windows 特定:隐藏控制台窗口标志
128+ #[ cfg( windows) ]
129+ trait CommandExt {
130+ fn creation_flags ( & mut self , flags : u32 ) -> & mut Self ;
131+ }
132+
133+ #[ cfg( windows) ]
134+ impl CommandExt for std:: process:: Command {
135+ fn creation_flags ( & mut self , flags : u32 ) -> & mut Self {
136+ use std:: os:: windows:: process:: CommandExt as WinCommandExt ;
137+ self . creation_flags ( flags)
138+ }
100139}
0 commit comments