Auto Start via TaskService

pull/3107/head
2dust 2023-01-04 17:17:43 +08:00
parent 4fc2ed32d2
commit ab6f5c21c8
1 changed files with 54 additions and 1 deletions

View File

@ -1,4 +1,5 @@
using Microsoft.Win32;
using Microsoft.Win32.TaskScheduler;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NLog;
@ -601,11 +602,22 @@ namespace v2rayN
//delete first
RegWriteValue(Global.AutoRunRegPath, autoRunName, "");
if (IsAdministrator())
{
AutoStart(autoRunName, "", "");
}
if (run)
{
string exePath = $"\"{GetExePath()}\"";
RegWriteValue(Global.AutoRunRegPath, autoRunName, exePath);
if (IsAdministrator())
{
AutoStart(autoRunName, exePath, "");
}
else
{
RegWriteValue(Global.AutoRunRegPath, autoRunName, exePath);
}
}
}
catch (Exception ex)
@ -740,6 +752,47 @@ namespace v2rayN
return false;
}
}
/// <summary>
/// Auto Start via TaskService
/// </summary>
/// <param name="taskName"></param>
/// <param name="fileName"></param>
/// <param name="description"></param>
/// <exception cref="ArgumentNullException"></exception>
public static void AutoStart(string taskName, string fileName, string description)
{
if (string.IsNullOrEmpty(taskName))
{
return;
}
string TaskName = taskName;
var logonUser = WindowsIdentity.GetCurrent().Name;
string taskDescription = description;
string deamonFileName = fileName;
using (var taskService = new TaskService())
{
var tasks = taskService.RootFolder.GetTasks(new Regex(TaskName));
foreach (var t in tasks)
{
taskService.RootFolder.DeleteTask(t.Name);
}
if (string.IsNullOrEmpty(fileName))
{
return;
}
var task = taskService.NewTask();
task.RegistrationInfo.Description = taskDescription;
task.Settings.DisallowStartIfOnBatteries = false;
task.Triggers.Add(new LogonTrigger { UserId = logonUser, Delay = TimeSpan.FromMinutes(1) });
task.Principal.RunLevel = TaskRunLevel.Highest;
task.Actions.Add(new ExecAction(deamonFileName));
taskService.RootFolder.RegisterTaskDefinition(TaskName, task);
}
}
#endregion