@@ -61,21 +61,45 @@ private static bool CheckLogonTask(bool alwaysRunAsAdministrator)
6161 {
6262 try
6363 {
64- // Check if the action is the same as the current executable path
65- // If not, we need to unschedule and reschedule the task
6664 if ( task . Definition . Actions . FirstOrDefault ( ) is Microsoft . Win32 . TaskScheduler . Action taskAction )
6765 {
6866 var action = taskAction . ToString ( ) . Trim ( ) ;
69- if ( ! action . Equals ( Constant . ExecutablePath , StringComparison . OrdinalIgnoreCase ) || // Path issue
70- ! CheckRunLevel ( task . Definition . Principal , alwaysRunAsAdministrator ) ) // Run level issue
67+ var pathCorrect = action . Equals ( Constant . ExecutablePath , StringComparison . OrdinalIgnoreCase ) ;
68+ var runLevelCorrect = CheckRunLevel ( task . Definition . Principal . RunLevel , alwaysRunAsAdministrator ) ;
69+
70+ if ( _isAdministrator )
71+ {
72+ // If path or run level is not correct, we need to unschedule and reschedule the task
73+ if ( ! pathCorrect || ! runLevelCorrect )
74+ {
75+ UnscheduleLogonTask ( ) ;
76+ ScheduleLogonTask ( alwaysRunAsAdministrator ) ;
77+ }
78+ }
79+ else
7180 {
72- UnscheduleLogonTask ( ) ;
73- ScheduleLogonTask ( alwaysRunAsAdministrator ) ;
81+ // If run level is not correct, we cannot edit it because we are not administrator
82+ if ( ! runLevelCorrect )
83+ {
84+ throw new UnauthorizedAccessException ( "Cannot edit task run level because the app is not running as administrator." ) ;
85+ }
86+
87+ // If run level is correct and path is not correct, we need to unschedule and reschedule the task
88+ if ( ! pathCorrect )
89+ {
90+ UnscheduleLogonTask ( ) ;
91+ ScheduleLogonTask ( alwaysRunAsAdministrator ) ;
92+ }
7493 }
7594 }
7695
7796 return true ;
7897 }
98+ catch ( UnauthorizedAccessException e )
99+ {
100+ App . API . LogError ( ClassName , $ "Failed to check logon task: { e } ") ;
101+ throw ; // Throw exception so that App.AutoStartup can show error message
102+ }
79103 catch ( Exception e )
80104 {
81105 App . API . LogError ( ClassName , $ "Failed to check logon task: { e } ") ;
@@ -86,9 +110,9 @@ private static bool CheckLogonTask(bool alwaysRunAsAdministrator)
86110 return false ;
87111 }
88112
89- private static bool CheckRunLevel ( TaskPrincipal tp , bool alwaysRunAsAdministrator )
113+ private static bool CheckRunLevel ( TaskRunLevel rl , bool alwaysRunAsAdministrator )
90114 {
91- return alwaysRunAsAdministrator ? tp . RunLevel == TaskRunLevel . Highest : tp . RunLevel != TaskRunLevel . Highest ;
115+ return alwaysRunAsAdministrator ? rl == TaskRunLevel . Highest : rl != TaskRunLevel . Highest ;
92116 }
93117
94118 private static bool CheckRegistry ( )
0 commit comments