How to set “run only if logged in” and “run as” wi

2019-05-02 11:29发布

问题:

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

回答1:

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!