-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathAppAutoStartService.cs
More file actions
462 lines (399 loc) · 13.3 KB
/
AppAutoStartService.cs
File metadata and controls
462 lines (399 loc) · 13.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
using System;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Xml;
using Microsoft.Win32;
namespace TidyWindow.App.Services;
/// <summary>
/// Manages TidyWindow auto-start registration using multiple fallback strategies
/// for maximum reliability across different Windows configurations.
/// </summary>
/// <remarks>
/// Strategy order:
/// 1. Task Scheduler via XML import (most reliable, supports elevated/delayed start)
/// 2. Task Scheduler via schtasks.exe command line (fallback)
/// 3. Registry Run key (fallback for non-admin or restricted environments)
/// </remarks>
public sealed class AppAutoStartService
{
private const string TaskFolderName = "TidyWindow";
private const string TaskName = "TidyWindowElevatedStartup";
private const string TaskFullName = $"\\{TaskFolderName}\\{TaskName}";
private const string RegistryRunKey = @"Software\Microsoft\Windows\CurrentVersion\Run";
private const string RegistryValueName = "TidyWindow";
private readonly IProcessRunner _processRunner;
public AppAutoStartService(IProcessRunner processRunner)
{
_processRunner = processRunner ?? throw new ArgumentNullException(nameof(processRunner));
}
/// <summary>
/// Gets whether TidyWindow is currently registered to start automatically.
/// Checks both Task Scheduler and Registry Run key.
/// </summary>
public bool IsEnabled
{
get
{
if (!OperatingSystem.IsWindows())
{
return false;
}
// Check Task Scheduler first
if (IsTaskRegistered())
{
return true;
}
// Fall back to registry check
return IsRegistryRunKeySet();
}
}
public bool TrySetEnabled(bool enabled, out string? error)
{
error = null;
try
{
if (!OperatingSystem.IsWindows())
{
return true;
}
var executablePath = ResolveExecutablePath();
if (enabled && executablePath is null)
{
error = "Unable to resolve the TidyWindow executable path.";
return false;
}
if (enabled)
{
return TryEnableStartup(executablePath!, out error);
}
return TryDisableStartup(out error);
}
catch (Exception ex)
{
error = ex.Message;
return false;
}
}
private bool TryEnableStartup(string executablePath, out string? error)
{
// Strategy 1: Try XML-based task creation (most reliable)
if (TryCreateTaskViaXml(executablePath, out error))
{
// Clean up any registry fallback entry
TryRemoveRegistryRunKey(out _);
return true;
}
// Strategy 2: Try schtasks.exe command line
if (TryCreateTaskViaCommandLine(executablePath, out error))
{
TryRemoveRegistryRunKey(out _);
return true;
}
// Strategy 3: Fall back to registry Run key (works without admin in some cases)
if (TrySetRegistryRunKey(executablePath, out error))
{
return true;
}
error = "Failed to register TidyWindow for startup using all available methods. " +
"Ensure the application is running with administrator privileges.";
return false;
}
private bool TryDisableStartup(out string? error)
{
var taskDeleted = TryDeleteTask(out var taskError);
var registryRemoved = TryRemoveRegistryRunKey(out var registryError);
if (taskDeleted && registryRemoved)
{
error = null;
return true;
}
// If both failed, combine errors
if (!taskDeleted && !registryRemoved)
{
error = $"Task Scheduler: {taskError}; Registry: {registryError}";
return false;
}
// At least one succeeded, consider it a success
error = null;
return true;
}
#region Task Scheduler - XML Import
private bool TryCreateTaskViaXml(string executablePath, out string? error)
{
string? tempXmlPath = null;
try
{
// First ensure the TidyWindow folder exists in Task Scheduler
EnsureTaskFolder();
var xml = GenerateTaskXml(executablePath);
tempXmlPath = Path.Combine(Path.GetTempPath(), $"TidyWindowTask_{Guid.NewGuid():N}.xml");
File.WriteAllText(tempXmlPath, xml, Encoding.Unicode);
// Import the task using schtasks /Create /XML
var arguments = $"/Create /TN \"{TaskFullName}\" /XML \"{tempXmlPath}\" /F";
var result = _processRunner.Run("schtasks.exe", arguments);
if (result.ExitCode == 0)
{
error = null;
return true;
}
error = CombineOutput(result.StandardOutput, result.StandardError);
return false;
}
catch (Exception ex)
{
error = ex.Message;
return false;
}
finally
{
if (tempXmlPath is not null)
{
try
{
File.Delete(tempXmlPath);
}
catch
{
// Best effort cleanup
}
}
}
}
private void EnsureTaskFolder()
{
// Create the TidyWindow folder in Task Scheduler if it doesn't exist
// This is done by creating a dummy task and immediately deleting it,
// or by using PowerShell - we'll use a simple check first
var checkResult = _processRunner.Run("schtasks.exe", $"/Query /TN \"\\{TaskFolderName}\" 2>nul");
if (checkResult.ExitCode != 0)
{
// Folder might not exist, but schtasks /Create will create it automatically
// when we create the task with the full path
}
}
private static string GenerateTaskXml(string executablePath)
{
// Escape the path for XML
var escapedPath = System.Security.SecurityElement.Escape(executablePath);
return $@"<?xml version=""1.0"" encoding=""UTF-16""?>
<Task version=""1.4"" xmlns=""http://schemas.microsoft.com/windows/2004/02/mit/task"">
<RegistrationInfo>
<Description>Launches TidyWindow at user sign-in for system maintenance and monitoring.</Description>
<Author>TidyWindow</Author>
</RegistrationInfo>
<Triggers>
<LogonTrigger>
<Enabled>true</Enabled>
<Delay>PT30S</Delay>
</LogonTrigger>
</Triggers>
<Principals>
<Principal id=""Author"">
<LogonType>InteractiveToken</LogonType>
<RunLevel>HighestAvailable</RunLevel>
</Principal>
</Principals>
<Settings>
<MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
<DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
<StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>
<AllowHardTerminate>true</AllowHardTerminate>
<StartWhenAvailable>true</StartWhenAvailable>
<RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
<IdleSettings>
<StopOnIdleEnd>false</StopOnIdleEnd>
<RestartOnIdle>false</RestartOnIdle>
</IdleSettings>
<AllowStartOnDemand>true</AllowStartOnDemand>
<Enabled>true</Enabled>
<Hidden>false</Hidden>
<RunOnlyIfIdle>false</RunOnlyIfIdle>
<DisallowStartOnRemoteAppSession>false</DisallowStartOnRemoteAppSession>
<UseUnifiedSchedulingEngine>true</UseUnifiedSchedulingEngine>
<WakeToRun>false</WakeToRun>
<ExecutionTimeLimit>PT0S</ExecutionTimeLimit>
<Priority>7</Priority>
</Settings>
<Actions Context=""Author"">
<Exec>
<Command>{escapedPath}</Command>
<Arguments>--minimized</Arguments>
</Exec>
</Actions>
</Task>";
}
#endregion
#region Task Scheduler - Command Line
private bool TryCreateTaskViaCommandLine(string executablePath, out string? error)
{
// Use simpler quoting that's more compatible across Windows versions
var command = $"\"{executablePath}\"";
var arguments = $"/Create /TN \"{TaskFullName}\" /F /SC ONLOGON /RL HIGHEST /TR \"{command} --minimized\" /DELAY 0000:30";
var result = _processRunner.Run("schtasks.exe", arguments);
if (result.ExitCode == 0)
{
error = null;
return true;
}
// Try without /DELAY if it failed (older Windows versions may not support it)
arguments = $"/Create /TN \"{TaskFullName}\" /F /SC ONLOGON /RL HIGHEST /TR \"{command} --minimized\"";
result = _processRunner.Run("schtasks.exe", arguments);
if (result.ExitCode == 0)
{
error = null;
return true;
}
error = CombineOutput(result.StandardOutput, result.StandardError);
return false;
}
#endregion
#region Registry Run Key Fallback
private bool TrySetRegistryRunKey(string executablePath, out string? error)
{
try
{
using var key = Registry.CurrentUser.OpenSubKey(RegistryRunKey, writable: true);
if (key is null)
{
error = "Could not open HKCU Run registry key.";
return false;
}
var value = $"\"{executablePath}\" --minimized";
key.SetValue(RegistryValueName, value, RegistryValueKind.String);
error = null;
return true;
}
catch (Exception ex)
{
error = $"Registry write failed: {ex.Message}";
return false;
}
}
private bool TryRemoveRegistryRunKey(out string? error)
{
try
{
using var key = Registry.CurrentUser.OpenSubKey(RegistryRunKey, writable: true);
if (key is null)
{
error = null;
return true; // Key doesn't exist, nothing to remove
}
var existingValue = key.GetValue(RegistryValueName);
if (existingValue is null)
{
error = null;
return true; // Value doesn't exist
}
key.DeleteValue(RegistryValueName, throwOnMissingValue: false);
error = null;
return true;
}
catch (Exception ex)
{
error = $"Registry delete failed: {ex.Message}";
return false;
}
}
private static bool IsRegistryRunKeySet()
{
try
{
using var key = Registry.CurrentUser.OpenSubKey(RegistryRunKey, writable: false);
if (key is null)
{
return false;
}
var value = key.GetValue(RegistryValueName) as string;
return !string.IsNullOrWhiteSpace(value) &&
value.Contains("TidyWindow", StringComparison.OrdinalIgnoreCase);
}
catch
{
return false;
}
}
#endregion
#region Task Query and Delete
private bool IsTaskRegistered()
{
try
{
var result = _processRunner.Run("schtasks.exe", $"/Query /TN \"{TaskFullName}\"");
return result.ExitCode == 0;
}
catch
{
return false;
}
}
private bool TryDeleteTask(out string? error)
{
var result = _processRunner.Run("schtasks.exe", $"/Delete /TN \"{TaskFullName}\" /F");
if (result.ExitCode == 0)
{
error = null;
return true;
}
var failure = CombineOutput(result.StandardOutput, result.StandardError);
if (IsMissingTaskMessage(failure))
{
error = null;
return true;
}
error = failure.Length == 0
? $"schtasks.exe exited with code {result.ExitCode}."
: failure;
return false;
}
#endregion
#region Helpers
private static bool IsMissingTaskMessage(string message)
{
if (string.IsNullOrWhiteSpace(message))
{
return false;
}
return message.Contains("cannot find", StringComparison.OrdinalIgnoreCase)
|| message.Contains("does not exist", StringComparison.OrdinalIgnoreCase)
|| message.Contains("not exist", StringComparison.OrdinalIgnoreCase)
|| message.Contains("cannot be found", StringComparison.OrdinalIgnoreCase);
}
private static string CombineOutput(string stdOut, string stdErr)
{
var hasErr = !string.IsNullOrWhiteSpace(stdErr);
var hasOut = !string.IsNullOrWhiteSpace(stdOut);
if (hasErr && hasOut)
{
return (stdErr + Environment.NewLine + stdOut).Trim();
}
if (hasErr)
{
return stdErr.Trim();
}
if (hasOut)
{
return stdOut.Trim();
}
return string.Empty;
}
private static string? ResolveExecutablePath()
{
try
{
using var process = Process.GetCurrentProcess();
var modulePath = process.MainModule?.FileName;
if (string.IsNullOrWhiteSpace(modulePath))
{
return null;
}
return Path.GetFullPath(modulePath);
}
catch
{
return null;
}
}
#endregion
}