@@ -103,6 +103,11 @@ private void SetupApplication()
103103 }
104104
105105 _cancellation = new CancellationTokenSource ( ) ;
106+
107+ _cancellation . Token . Register ( ( ) => {
108+ _cancellation . Dispose ( ) ;
109+ if ( _exitRequested ) { Environment . Exit ( 0 ) ; }
110+ } ) ;
106111 }
107112
108113
@@ -142,6 +147,8 @@ private void ConfigureServices(IServiceCollection service)
142147
143148 #region System Tray Icon
144149
150+ private bool _exitRequested = false ;
151+
145152 private void InitializeTrayIcon ( )
146153 {
147154 _trayMenu = new ContextMenu ( ) ;
@@ -152,7 +159,10 @@ private void InitializeTrayIcon()
152159
153160 _trayMenu . Items . Add ( "Reset" , null , OnResetClickedOnClick ) ;
154161 _trayMenu . Items . Add ( "-" ) ;
155- _trayMenu . Items . Add ( "Exit" , null , ( sender , args ) => Application . Exit ( ) ) ;
162+ _trayMenu . Items . Add ( "Exit" , null , ( sender , args ) => {
163+ _exitRequested = true ;
164+ Application . Exit ( ) ;
165+ } ) ;
156166
157167 _trayIcon = new NotifyIcon
158168 {
@@ -176,6 +186,13 @@ private void InitializeTrayIcon()
176186 lastActiveWin = GetForegroundWindow ( ) ;
177187 } ;
178188 _trayIcon . BalloonTipClosed += ( sender , args ) => _notificationOpen = false ;
189+
190+ this . FormClosing += ( sender , e ) =>
191+ {
192+ // Hide and dispose the icon
193+ _trayIcon . Visible = false ;
194+ _trayIcon . Dispose ( ) ;
195+ } ;
179196 }
180197
181198 private void OnAutoStartClick ( object sender , EventArgs e )
0 commit comments