Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set "run only if logged in" and "run as" with TaskScheduler in C#?

I've got code that uses the C# TaskManager object to create a task. On Windows 7 it works fine but on Windows XP (and presumably other Windows) it doesn't work at all because the default user for the task is system and thus there's no session for the GUI to be displayed. If I modify the created task manually in the control panel widget to set the job to run only when user is logged in and only for the particular user, then everything works perfectly. But despite hours of searching I see no options for setting these options in the C# objects. Anyone know a solution with the existing objects? I'd hate to rewrite everything to manually run the scheduler EXE and pass in stuff by command-line.

Q

like image 260
Quinxy von Besiex Avatar asked Oct 09 '22 11:10

Quinxy von Besiex


1 Answers

Okay, I figured out the answer!

I didn't realize it but I had been using a third-party Task Scheduler Managed Wrapper (it'd been a while since I wrote that part of my code) and that explains why help was hard to find! I stumbled across that page a moment ago and right there in their examples was just what I needed! The detailed solution in context can be found here, but the key part is:

// Create a new task definition and assign properties
TaskDefinition td = ts.NewTask();
td.Principal.UserId = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
td.Principal.LogonType = TaskLogonType.InteractiveToken;

Thanks for trying to help!

like image 83
Quinxy von Besiex Avatar answered Oct 13 '22 12:10

Quinxy von Besiex