/// <summary> /// Adds a task that will launch a program every time someone logs in. The program must have privilege 'AsInvoker' and NOT 'Highest'. /// </summary> /// <param name="taskName">Task name, whatever you want that can be a file name.</param> /// <param name="exeName">The full path to the program to launch.</param> /// <param name="runLevel">The program privilege when launched.</param> /// <returns>True if successful; otherwise, false.</returns> public static bool AddTask(string taskName, string exeName, TaskRunLevel runLevel) { Contract.RequireNotNull(taskName, out string TaskName); Contract.RequireNotNull(exeName, out string ExeName); try { // Remove forbidden characters since the name must not contain them. char[] InvalidChars = Path.GetInvalidFileNameChars(); foreach (char InvalidChar in InvalidChars) { TaskName = TaskName.Replace(InvalidChar, ' '); } // Create a task that launch a program when logging in. using TaskService Scheduler = new TaskService(); using Trigger LogonTrigger = Trigger.CreateTrigger(TaskTriggerType.Logon); using ExecAction RunAction = (ExecAction)Microsoft.Win32.TaskScheduler.Action.CreateAction(TaskActionType.Execute); RunAction.Path = ExeName; // Try with a task name (mandatory on new versions of Windows) if (AddTaskToScheduler(Scheduler, TaskName, LogonTrigger, RunAction, runLevel)) { return(true); } // Try without a task name (mandatory on old versions of Windows) if (AddTaskToScheduler(Scheduler, null, LogonTrigger, RunAction, runLevel)) { return(true); } } catch (Exception e) { throw new AddTaskFailedException(e); } return(false); }