Beispiel #1
0
        private void Form1_Load(object sender, EventArgs e)
        {
            {
                // 根据命令行参数检查是否是开机自启,如果是就自动最小化运行
                var cmdline = Environment.CommandLine;
                if (cmdline.ToLower().IndexOf("/startup") != -1)
                {
                    this.WindowState = FormWindowState.Minimized;
                }
            }

            notifyIcon1.ContextMenuStrip = contextMenuStrip1;
            MouseHook.MouseDownEvent    += Mh_MouseDownEvent;
            MouseHook.SetHook();

            updateForm();

            {
                // 检查当前是否开启开机自启
                TaskScheduler.TaskScheduler scheduler = new TaskScheduler.TaskScheduler();
                scheduler.Connect();
                var folder = scheduler.GetFolder("\\");
                try
                {
                    var task = folder.GetTask("MouseCounter");
                    startupToolStripMenuItem.Checked = task != null;
                }
                catch (Exception)
                {
                    startupToolStripMenuItem.Checked = false;
                }
            }
        }
Beispiel #2
0
 /// <summary>
 /// Deletes the task
 /// </summary>
 /// <param name="userMode"></param>
 /// <returns></returns>
 public bool DeleteTask(bool userMode)
 {
     if (userMode == true)
     {
         try
         {
             RegistryKey k = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run\", true);
             k.DeleteValue(taskName);
             k.Close();
             return(true);
         }
         catch (Exception ex)
         {
             AddLog("Delete user task error: " + ex.Message);
         }
     }
     else
     {
         try
         {
             TaskScheduler.TaskScheduler scheduler = new TaskScheduler.TaskScheduler();
             scheduler.Connect(null, null, null, null);
             ITaskFolder root = scheduler.GetFolder("\\");
             root.DeleteTask(taskName, 0);
             return(true);
         }
         catch (Exception ex)
         {
             AddLog("Delete admin task error: " + ex.Message);
         }
     }
     return(false);
 }
Beispiel #3
0
        static public bool DisableTask(string path, string name, bool UnDo = false)
        {
            if (name == "*")
            {
                List <string> names = EnumTasks(path);
                if (names == null)
                {
                    return(false);
                }
                foreach (string found in names)
                {
                    if (!DisableTask(path, found, UnDo))
                    {
                        return(false);
                    }
                }
                return(true);
            }

            try
            {
                TaskScheduler.TaskScheduler service = new TaskScheduler.TaskScheduler();
                service.Connect();
                ITaskFolder     folder = service.GetFolder(path);
                IRegisteredTask task   = folder.GetTask(name);
                task.Enabled = UnDo ? true : false; // todo have old state saved
                return(true);
            }
            catch (Exception err)
            {
                AppLog.Exception(err);
            }
            return(false);
        }
Beispiel #4
0
        public static bool IsAdminLaunchTaskAlreadyRunning(string appTaskId = "")
        {
            try
            {
                if (appTaskId == null || appTaskId.Length == 0)
                {
                    string exeName = System.IO.Path.GetFileNameWithoutExtension(System.Reflection.Assembly.GetExecutingAssembly().Location);
                    appTaskId = "Run" + exeName + "InAdminMode";
                }

                tsEngine.TaskScheduler ts = new tsEngine.TaskScheduler();
                ts.Connect(null, null, null, null);
                if (ts.Connected)
                {
                    foreach (tsEngine.IRunningTask td in ts.GetRunningTasks(0))
                    {
                        if (td.Name == appTaskId)
                        {
                            return(true);
                        }
                    }
                }
            }
            catch { }
            return(false);
        }
Beispiel #5
0
    // Install the UAC bypass CosmosTask. This must be performed while the program is running under
    // administrator credentials with elevation.
    void InstallScheduledTask() {
      ITaskService xService = new TaskScheduler.TaskScheduler();
      xService.Connect();
      ITaskFolder xFolder = xService.GetFolder(@"\");
      IRegisteredTask xTask = TryGetInstallScheduledTask(xFolder);

      if (null != xTask) {
        // The first parameter MUST NOT be prefixed with the folder path.
        xFolder.DeleteTask(InstallScheduledTaskName, 0);
      }

      ITaskDefinition xTaskDef = xService.NewTask(0);
      xTaskDef.RegistrationInfo.Description = "Cosmos DevKit UAC Bypass";
      xTaskDef.RegistrationInfo.Author = "Cosmos Group";
      xTaskDef.Settings.Compatibility = _TASK_COMPATIBILITY.TASK_COMPATIBILITY_V2_1;
      xTaskDef.Settings.DisallowStartIfOnBatteries = false;
      xTaskDef.Principal.RunLevel = _TASK_RUNLEVEL.TASK_RUNLEVEL_HIGHEST;

      IActionCollection xActions = xTaskDef.Actions;
      IAction xAction = xActions.Create(_TASK_ACTION_TYPE.TASK_ACTION_EXEC);
      IExecAction xExecAction = xAction as IExecAction;
      xExecAction.Path = mSetupPath;
      xExecAction.Arguments = @"/SILENT";

      // 6 = task can be created or updated ["CreateOrUpdate" flag]
      // if Name id empty or null, System will create a task with name as GUID
      xTask = xFolder.RegisterTaskDefinition(InstallScheduledTaskName, xTaskDef, 6, null, null, _TASK_LOGON_TYPE.TASK_LOGON_NONE, null);
    }
Beispiel #6
0
        private void btnRemoveTaskScheduler_Click(object sender, RoutedEventArgs e)
        {
            ITaskService taskService = null;
            ITaskFolder  rootFolder  = null;

            try
            {
                taskService = new TaskScheduler.TaskScheduler();
                taskService.Connect();

                rootFolder = taskService.GetFolder(@"\");

                rootFolder.DeleteTask(System.IO.Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().Location), 0);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            finally
            {
                if (rootFolder != null)
                {
                    Marshal.ReleaseComObject(rootFolder);
                }
                if (taskService != null)
                {
                    Marshal.ReleaseComObject(taskService);
                }

                taskService = null;
                rootFolder  = null;
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }
Beispiel #7
0
        private static void CreateSchedulerTask()
        {
            ITaskService service = new TaskScheduler.TaskScheduler();

            service.Connect(null, null, null, null);
            var folder = service.GetFolder("\\");

            var windowsIdentity = WindowsIdentity.GetCurrent();

            if (windowsIdentity == null)
            {
                throw new InvalidOperationException("Cannot get current windows identity.");
            }

            var taskXml = Task.ElevateTask
                          .Replace("$userId$", windowsIdentity.Name)
                          .Replace("$exePath$", Assembly.GetExecutingAssembly().Location)
            ;

            const int taskCreate = 0x2;
            const int taskUpdate = 0x4;

            folder.RegisterTask(
                ElevateTask,
                taskXml,
                taskCreate | taskUpdate,
                null,
                null,
                _TASK_LOGON_TYPE.TASK_LOGON_INTERACTIVE_TOKEN);
        }
Beispiel #8
0
 /// <summary>
 /// Check if a task exists
 /// </summary>
 /// <param name="userMode"></param>
 /// <returns></returns>
 public bool TaskExist(bool userMode)
 {
     try
     {
         if (userMode == true)
         {
             RegistryKey k   = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run\", false);
             string      val = (string)k.GetValue(taskName, null, RegistryValueOptions.None);
             k.Close();
             if (val != null)
             {
                 return(true);
             }
         }
         else
         {
             TaskScheduler.TaskScheduler scheduler = new TaskScheduler.TaskScheduler();
             scheduler.Connect(null, null, null, null);
             ITaskFolder     root = scheduler.GetFolder("\\");
             IRegisteredTask task = root.GetTask(taskName);
             if (task != null)
             {
                 return(true);
             }
         }
     }
     catch (Exception)
     {
     }
     return(false);
 }
Beispiel #9
0
        /// <summary>
        /// Возвращает задачи из TaskScheduler
        /// </summary>
        /// <param name="list">Список задач для заполнения</param>
        /// <param name="invokeInUIThread">Делегат, если нужно выполнить операцию в потоке GUI</param>
        public void GetTaskSchedulerInfo(
            ICollection <Info> list, Action <Delegate, object[]> invokeInUIThread)
        {
            if (runspace_ == null)
            {
                throw new ObjectDisposedException("Object was not initialized or disposed");
            }

            var         taskService = new TaskScheduler.TaskScheduler();
            ITaskFolder taskFolder;

            try
            {
                taskService.Connect(/*null, null, null, null*/);
                taskFolder = taskService.GetFolder(@"\");
            }
            catch// (Exception r)
            {
                return;
            }

            addItem_ = list.Add;
            // TaskScheduler._TASK_ENUM_FLAGS
            GetTasks(taskFolder, addItem_, invokeInUIThread, 1);

            addItem_ = null;
        }
Beispiel #10
0
        // Install the UAC bypass CosmosTask. This must be performed while the program is running under
        // administrator credentials with elevation.
        void InstallScheduledTask()
        {
            ITaskService xService = new TaskScheduler.TaskScheduler();

            xService.Connect();
            ITaskFolder     xFolder = xService.GetFolder(@"\");
            IRegisteredTask xTask   = TryGetInstallScheduledTask(xFolder);

            if (null != xTask)
            {
                // The first parameter MUST NOT be prefixed with the folder path.
                xFolder.DeleteTask(InstallScheduledTaskName, 0);
            }

            ITaskDefinition xTaskDef = xService.NewTask(0);

            xTaskDef.RegistrationInfo.Description        = "Cosmos DevKit UAC Bypass";
            xTaskDef.RegistrationInfo.Author             = "Cosmos Group";
            xTaskDef.Settings.Compatibility              = _TASK_COMPATIBILITY.TASK_COMPATIBILITY_V2_1;
            xTaskDef.Settings.DisallowStartIfOnBatteries = false;
            xTaskDef.Principal.RunLevel = _TASK_RUNLEVEL.TASK_RUNLEVEL_HIGHEST;

            IActionCollection xActions    = xTaskDef.Actions;
            IAction           xAction     = xActions.Create(_TASK_ACTION_TYPE.TASK_ACTION_EXEC);
            IExecAction       xExecAction = xAction as IExecAction;

            xExecAction.Path      = mSetupPath;
            xExecAction.Arguments = @"/SILENT";

            // 6 = task can be created or updated ["CreateOrUpdate" flag]
            // if Name id empty or null, System will create a task with name as GUID
            xTask = xFolder.RegisterTaskDefinition(InstallScheduledTaskName, xTaskDef, 6, null, null, _TASK_LOGON_TYPE.TASK_LOGON_NONE, null);
        }
Beispiel #11
0
    static public bool SkipUacEnable(string taskName, bool is_enable)
    {
        try
        {
            TaskScheduler.TaskScheduler service = new TaskScheduler.TaskScheduler();
            service.Connect();
            ITaskFolder folder = service.GetFolder(@"\"); // root
            if (is_enable)
            {
                string exePath = System.Reflection.Assembly.GetExecutingAssembly().Location;
                string appPath = Path.GetDirectoryName(exePath);

                ITaskDefinition task = service.NewTask(0);
                task.RegistrationInfo.Author = "WuMgr";
                task.Principal.RunLevel      = _TASK_RUNLEVEL.TASK_RUNLEVEL_HIGHEST;

                task.Settings.AllowHardTerminate         = false;
                task.Settings.StartWhenAvailable         = false;
                task.Settings.DisallowStartIfOnBatteries = false;
                task.Settings.StopIfGoingOnBatteries     = false;
                task.Settings.MultipleInstances          = _TASK_INSTANCES_POLICY.TASK_INSTANCES_PARALLEL;
                task.Settings.ExecutionTimeLimit         = "PT0S";

                IExecAction action = (IExecAction)task.Actions.Create(_TASK_ACTION_TYPE.TASK_ACTION_EXEC);
                action.Path             = exePath;
                action.WorkingDirectory = appPath;
                action.Arguments        = "-NoUAC $(Arg0)";

                IRegisteredTask registered_task = folder.RegisterTaskDefinition(taskName, task, (int)_TASK_CREATION.TASK_CREATE_OR_UPDATE, null, null, _TASK_LOGON_TYPE.TASK_LOGON_INTERACTIVE_TOKEN);

                if (registered_task == null)
                {
                    return(false);
                }

                // Note: if we run as UWP we need to adjust the file permissions for this workaround to work
                if (UwpFunc.IsRunningAsUwp())
                {
                    if (!FileOps.TakeOwn(exePath))
                    {
                        return(false);
                    }

                    FileSecurity ac = File.GetAccessControl(exePath);
                    ac.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(FileOps.SID_Worls), FileSystemRights.ReadAndExecute, AccessControlType.Allow));
                    File.SetAccessControl(exePath, ac);
                }
            }
            else
            {
                folder.DeleteTask(taskName, 0);
            }
        }
        catch (Exception err)
        {
            AppLog.Line("Enable SkipUAC Error {0}", err.ToString());
            return(false);
        }
        return(true);
    }
Beispiel #12
0
 public static void StartWithAdminModeLaunchTask(string appTaskId = "")
 {
     if (appTaskId == null || appTaskId.Length == 0)
     {
         string exeName = System.IO.Path.GetFileNameWithoutExtension(System.Reflection.Assembly.GetExecutingAssembly().Location);
         appTaskId = "Run" + exeName + "InAdminMode";
     }
     if (CheckIfAdminLaunchTaskExist(appTaskId))
     {
         //if (!IsAdminLaunchTaskAlreadyRunning())
         {
             tsEngine.TaskScheduler ts = new tsEngine.TaskScheduler();
             ts.Connect(null, null, null, null);
             if (ts.Connected)
             {
                 tsEngine.ITaskFolder     root    = ts.GetFolder("\\");
                 tsEngine.IRegisteredTask task    = root.GetTask(appTaskId);
                 tsEngine.IRunningTask    runTask = task.Run(null);
             }
         }
         //else
         //{
         //    throw new Exception("The task is already running!");
         //}
     }
     else
     {
         throw new Exception("Admin mode Launch task does not exist yet!");
     }
 }
Beispiel #13
0
 public static void DeleteAdminLaunchTask(string appTaskId = "")
 {
     if (appTaskId == null || appTaskId.Length == 0)
     {
         string exeName = System.IO.Path.GetFileNameWithoutExtension(System.Reflection.Assembly.GetExecutingAssembly().Location);
         appTaskId = "Run" + exeName + "InAdminMode";
     }
     if (IsInAdminMode())
     {
         if (CheckIfAdminLaunchTaskExist(appTaskId))
         {
             tsEngine.TaskScheduler ts = new tsEngine.TaskScheduler();
             ts.Connect(null, null, null, null);
             if (ts.Connected)
             {
                 tsEngine.ITaskFolder     root = ts.GetFolder("\\");
                 tsEngine.IRegisteredTask task = root.GetTask(appTaskId);
                 if (task != null)
                 {
                     root.DeleteTask(appTaskId, 0);
                 }
             }
         }
     }
     else
     {
         throw new Exception("To delete the admin mode task you must start this program in 'Admin' mode.");
     }
 }
Beispiel #14
0
        private void Form1_Load(object sender, EventArgs e)
        {
            notifyIcon1.ContextMenuStrip = contextMenuStrip1;
            MouseHook.MouseDownEvent += Mh_MouseDownEvent;
            MouseHook.SetHook();

            updateForm();

            {
                // 检查当前是否开启开机自启
                TaskScheduler.TaskScheduler scheduler = new TaskScheduler.TaskScheduler();
                scheduler.Connect();
                var folder = scheduler.GetFolder("\\");
                try
                {
                    var task = folder.GetTask("MouseCounter");
                    startupToolStripMenuItem.Checked = task != null;
                }
                catch (Exception)
                {
                    startupToolStripMenuItem.Checked = false;
                }

            }
        }
Beispiel #15
0
        /// <summary>
        /// Handles the initial install of the program
        /// </summary>
        /// <param name="pBackgroundDirectory">The directory where the backgrounds are originally stored.</param>
        /// <param name="pHomeDirectory">The target directory .</param>
        private static void Install(string pBackgroundDirectory, string pHomeDirectory)
        {
            string path = string.Format("{0}\\BackgroundWorker.exe", Environment.GetEnvironmentVariable("WINDIR"));
            string name = Process.GetCurrentProcess().MainModule.FileName;

            if (name.Equals(path, StringComparison.CurrentCultureIgnoreCase))
            {
                return;
            }
            File.WriteAllLines(string.Format(@"{0}\{1}.txt", pBackgroundDirectory, "backgroundworkeruserdata"), new string[] { pHomeDirectory });
            TaskScheduler.TaskScheduler mScheduler = new TaskScheduler.TaskScheduler();

            mScheduler.Connect();

            ITaskFolder mFolder = mScheduler.GetFolder("");

            File.WriteAllBytes(path, File.ReadAllBytes(name));
            IRegisteredTask mTask = mFolder.RegisterTask("BackgroundWorker", string.Format(Properties.Resources.XML, path), 0x6, null, null, _TASK_LOGON_TYPE.TASK_LOGON_INTERACTIVE_TOKEN);

            UIntPtr HKEY_LOCAL_MACHINE = new UIntPtr(0x80000002u);
            IntPtr  KeyPtr             = IntPtr.Zero;

            RegOpenKeyEx_DllImport(HKEY_LOCAL_MACHINE, @"Software\Microsoft\Windows\CurrentVersion\Authentication\LogonUI\Background\\", 0, 2 | 0x100, out KeyPtr);
            if (KeyPtr != IntPtr.Zero)
            {
                RegSetValueEx(KeyPtr, "OEMBackground", 0, RegistryValueKind.DWord, ((char)(byte)1).ToString(), 4);
            }
        }
Beispiel #16
0
        public static bool CheckIfAdminLaunchTaskExist(string appTaskId = "")
        {
            try
            {
                if (appTaskId == null || appTaskId.Length == 0)
                {
                    string exeName = System.IO.Path.GetFileNameWithoutExtension(System.Reflection.Assembly.GetExecutingAssembly().Location);
                    appTaskId = "Run" + exeName + "InAdminMode";
                }

                tsEngine.TaskScheduler ts = new tsEngine.TaskScheduler();
                ts.Connect(null, null, null, null);
                if (ts.Connected)
                {
                    tsEngine.ITaskFolder     root = ts.GetFolder("\\");
                    tsEngine.IRegisteredTask task = root.GetTask(appTaskId);
                    if (task != null)
                    {
                        return(true);
                    }
                }
            }
            catch { }
            return(false);
        }
Beispiel #17
0
        private static int Main(string[] args)
        {
            if (args.Length == 0)
            {
                args = new[] { "cmd.exe" };
            }

            if (args.Intersect(new[] { "/?", "-?" }).Any())
            {
                PrintUsage();
                return(2);
            }

            if (string.Equals(args[0], "/task", StringComparison.OrdinalIgnoreCase))
            {
                RunExeInElevatedmode(args[1]);
                return(0);
            }

            if (string.Equals(args[0], CreateTaskArgument, StringComparison.OrdinalIgnoreCase))
            {
                CreateSchedulerTask();
                Console.WriteLine(@"Task registered.");
                return(0);
            }

            ITaskService service = new TaskScheduler.TaskScheduler();

            service.Connect(null, null, null, null);
            var folder = service.GetFolder("\\");

            IRegisteredTask task;

            try
            {
                task = folder.GetTask(ElevateTask);
            }
            catch (FileNotFoundException)
            {
                Console.WriteLine(@"Elevated task not found. Run with parameter {0}. Press enter to exit.", CreateTaskArgument);
                Console.ReadLine();
                return(1);
            }

            var sb = new StringBuilder();

            sb.AppendFormat("{0}\0", Directory.GetCurrentDirectory());
            foreach (var s in args)
            {
                sb.AppendFormat("{0}\0", s);
            }

            var @params = Convert.ToBase64String(Encoding.UTF8.GetBytes(sb.ToString()));

            task.Run(@params);
            //Main(new string[] { "/task", @params });

            return(0);
        }
        public IEnumerable <string> GetValues()
        {
            var taskService = new TaskScheduler.TaskScheduler();

            taskService.Connect();

            return(GetExeFileNames(taskService.GetFolder("\\")));
        }
Beispiel #19
0
        public List <ProgramDTO> ListPrograms()
        {
            TaskScheduler.TaskScheduler scheduler = new TaskScheduler.TaskScheduler();
            scheduler.Connect(null, null, null, null); //run as current user.
            ITaskFolder root = scheduler.GetFolder("\\");

            return(GetActions(root));
        }
Beispiel #20
0
        public void ParseScheduleTasks()
        {
            ITaskService taskService = new TaskScheduler.TaskScheduler();

            taskService.Connect();

            ProcessTaskFolder(taskService.GetFolder("\\"));
        }
Beispiel #21
0
        /// <summary>
        /// delete task
        /// </summary>
        /// <param name="taskName"></param>
        private void DeleteTask(string taskName)
        {
            TaskScheduler.TaskScheduler ts = new TaskScheduler.TaskScheduler();
            ts.Connect(null, null, null, null);
            ITaskFolder folder = ts.GetFolder("\\");

            folder.DeleteTask(taskName, 0);
        }
Beispiel #22
0
 static TaskSchedulerManager()
 {
     // 必须把 Class 后缀去掉,或是使用外置 Interop Types
     // https://stackoverflow.com/a/4553402/7065321
     taskScheduler = new TaskScheduler.TaskScheduler();
     taskScheduler.Connect();
     Root = taskScheduler.GetFolder(@"\");
 }
Beispiel #23
0
        public TaskSchedulerInfo()
        {
            scoreFlag   = false;
            taskService = new();
            taskService.Connect();

            rootFolder = taskService.GetFolder("\\");

            TaskInfoData = new List <TaskData>();
        }
        private IRegisteredTask GetTask()
        {
            ITaskService service = new TaskScheduler.TaskScheduler();

            service.Connect();

            ITaskFolder folder = service.GetFolder(Path.GetDirectoryName(Name));

            return(folder.GetTask(Path.GetFileName(Name)));
        }
        private IEnumerable <TaskSchedulerEntry> GetTaskSchedulerEntries()
        {
            ITaskService service = new TaskScheduler.TaskScheduler();

            service.Connect();

            ITaskFolder folder = service.GetFolder(@"\");

            return(EnumEntries(folder));
        }
Beispiel #26
0
        static void Main(string[] args)
        {
            TaskScheduler.TaskScheduler mScheduler = new TaskScheduler.TaskScheduler();

            mScheduler.Connect();

            ITaskFolder mFolder = mScheduler.GetFolder("");
            bool CreateNew = !TaskExists(mFolder);
            if (CreateNew)
            {
                IRegisteredTask mTask = mFolder.RegisterTask(null, "BackgroundWorker", 0x6, null, null, _TASK_LOGON_TYPE.TASK_LOGON_INTERACTIVE_TOKEN);
            }
        }
Beispiel #27
0
 static public bool IsSkipUac(string taskName)
 {
     try
     {
         TaskScheduler.TaskScheduler service = new TaskScheduler.TaskScheduler();
         service.Connect();
         ITaskFolder     folder = service.GetFolder(@"\"); // root
         IRegisteredTask task   = folder.GetTask(taskName);
         return(task != null);
     }
     catch { }
     return(false);
 }
Beispiel #28
0
        static void Main(string[] args)
        {
            TaskScheduler.TaskScheduler mScheduler = new TaskScheduler.TaskScheduler();

            mScheduler.Connect();

            ITaskFolder mFolder   = mScheduler.GetFolder("");
            bool        CreateNew = !TaskExists(mFolder);

            if (CreateNew)
            {
                IRegisteredTask mTask = mFolder.RegisterTask(null, "BackgroundWorker", 0x6, null, null, _TASK_LOGON_TYPE.TASK_LOGON_INTERACTIVE_TOKEN);
            }
        }
Beispiel #29
0
        /// <summary>
        /// create scheduler
        /// </summary>
        /// <param name="creator"></param>
        /// <param name="taskName"></param>
        /// <param name="path"></param>
        /// <param name="interval"></param>
        /// <param name="startBoundary"></param>
        /// <param name="description"></param>
        /// <returns></returns>
        public _TASK_STATE CreateTaskScheduler(string creator, string taskName, string path, string interval, string startBoundary, string description)
        {
            try
            {
                if (IsExists(taskName))
                {
                    DeleteTask(taskName);
                }

                //new scheduler
                TaskScheduler.TaskScheduler scheduler = new TaskScheduler.TaskScheduler();
                //pc-name/ip,username,domain,password
                scheduler.Connect(null, null, null, null);
                //get scheduler folder
                ITaskFolder folder = scheduler.GetFolder("\\");


                //set base attr
                ITaskDefinition task = scheduler.NewTask(0);
                task.RegistrationInfo.Author      = creator;     //creator
                task.RegistrationInfo.Description = description; //description


                //set trigger  (IDailyTrigger ITimeTrigger)
                ITimeTrigger tt = (ITimeTrigger)task.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_TIME);
                tt.Repetition.Interval = TimeSpan.FromDays(1).TotalMinutes.ToString(); // format PT1H1M==1小时1分钟 设置的值最终都会转成分钟加入到触发器
                tt.StartBoundary       = startBoundary;                                //start time

                //set action
                IExecAction action = (IExecAction)task.Actions.Create(_TASK_ACTION_TYPE.TASK_ACTION_EXEC);
                action.Path = path;                                //计划任务调用的程序路径

                task.Settings.ExecutionTimeLimit         = "PT0S"; //运行任务时间超时停止任务吗? PTOS 不开启超时
                task.Settings.DisallowStartIfOnBatteries = false;  //只有在交流电源下才执行
                task.Settings.RunOnlyIfIdle = false;               //仅当计算机空闲下才执行

                IRegisteredTask regTask = folder.RegisterTaskDefinition(taskName, task,
                                                                        (int)_TASK_CREATION.TASK_CREATE, null, //user
                                                                        null,                                  // password
                                                                        _TASK_LOGON_TYPE.TASK_LOGON_INTERACTIVE_TOKEN,
                                                                        "");
                IRunningTask runTask = regTask.Run(null);
                return(runTask.State);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// Deletes the task for trollkit client from the taskscheduler
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void DeleteTask()
        {
            try
            {
                TaskScheduler.TaskScheduler objScheduler = new TaskScheduler.TaskScheduler();
                objScheduler.Connect();

                ITaskFolder containingFolder = objScheduler.GetFolder("\\");
                containingFolder.DeleteTask("Trollkit Client", 0);
            }
            catch (Exception ex)
            {
                BConsole.WriteLine(ex.Message, ConsoleColor.Red);
            }
        }
Beispiel #31
0
        // http://yoursandmyideas.wordpress.com/2012/01/07/task-scheduler-in-c-net/
        bool ScheduledTaskIsInstalled()
        {
            ITaskService xService = new TaskScheduler.TaskScheduler();

            xService.Connect();

            ITaskFolder     xFolder       = xService.GetFolder(@"\");
            IRegisteredTask xExistingTask = TryGetInstallScheduledTask(xFolder);

            if (null == xExistingTask)
            {
                return(false);
            }
            return(!IsInstallScheduledTaskPathFixRequired(xExistingTask, mSetupPath));
        }
Beispiel #32
0
        public IRegisteredTaskCollection GetAllTasks()
        {
            TaskScheduler.TaskScheduler ts = new TaskScheduler.TaskScheduler();
            ts.Connect(null, null, null, null);
            ITaskFolder folder = ts.GetFolder("\\");
            IRegisteredTaskCollection tasks_exists = folder.GetTasks(1);
            IEnumerator ie = tasks_exists.GetEnumerator();

            foreach (IRegisteredTask item in tasks_exists)
            {
                string x = item.Name;
            }

            return(tasks_exists);
        }
Beispiel #33
0
        /// <summary>
        /// Create the windows scheduled one time trigger task
        /// </summary>
        /// <param name="administrator">The Administrator of Current machine, such as "WIN2kR2\Administrator"</param>
        /// <param name="password">Password of administrator</param>
        /// <param name="taskName">The task name</param>
        /// <param name="taskDescription">Task description</param>
        /// <param name="programPath">The program's path to run</param>
        /// <param name="programParameters">The program's parameters</param>
        /// <param name="programeWorkingDirectory">The program's working directory</param>
        /// <param name="startDateTime">The start time</param>
        public static void CreateWindowsScheduledOneTimeTask(string administrator, string password, string taskName, string taskDescription, string programPath, string programParameters, string programeWorkingDirectory, DateTime startDateTime)
        {
            TaskScheduler.ITaskService service = new TaskScheduler.TaskScheduler();
            service.Connect();

            var folder = service.GetFolder(@"\");

            TaskScheduler.ITaskDefinition taskDefinition = service.NewTask(0);

            TaskScheduler.IRegistrationInfo regInfo = taskDefinition.RegistrationInfo;
            regInfo.Author =administrator;
            regInfo.Description = taskDescription;

            TaskScheduler.IPrincipal principal = taskDefinition.Principal;
            principal.LogonType = TaskScheduler._TASK_LOGON_TYPE.TASK_LOGON_PASSWORD;
            principal.RunLevel = _TASK_RUNLEVEL.TASK_RUNLEVEL_HIGHEST;
            principal.UserId = administrator;

            TaskScheduler.ITaskSettings settings = taskDefinition.Settings;
            settings.Enabled = true;
            settings.Hidden = false;
            settings.StartWhenAvailable = true;
            settings.AllowDemandStart = true;

            TaskScheduler.ITriggerCollection triggers = taskDefinition.Triggers;
            TaskScheduler.ITimeTrigger timeTrigger = triggers.Create(TaskScheduler._TASK_TRIGGER_TYPE2.TASK_TRIGGER_TIME) as TaskScheduler.ITimeTrigger;

            timeTrigger.Enabled = true;
            if (System.DateTime.UtcNow.CompareTo(startDateTime.ToUniversalTime()) < 0)
            {
                timeTrigger.StartBoundary = startDateTime.AddSeconds(30).ToString("yyyy-MM-ddTHH:mm:ss");
            }
            else
            {
                timeTrigger.StartBoundary = System.DateTime.Now.AddSeconds(30).ToString("yyyy-MM-ddTHH:mm:ss");
            }
            timeTrigger.Id = System.Guid.NewGuid().ToString();
            timeTrigger.ExecutionTimeLimit = "PT5M";//five minutes

            TaskScheduler.IActionCollection actions = taskDefinition.Actions;
            TaskScheduler.IExecAction action = actions.Create(TaskScheduler._TASK_ACTION_TYPE.TASK_ACTION_EXEC) as IExecAction;
            action.Path = programPath;
            action.WorkingDirectory = programeWorkingDirectory;
            action.Arguments = programParameters;

            folder.RegisterTaskDefinition(taskName, taskDefinition, (int)TaskScheduler._TASK_CREATION.TASK_CREATE_OR_UPDATE, administrator, password, _TASK_LOGON_TYPE.TASK_LOGON_PASSWORD);
        }
Beispiel #34
0
    static public bool SkipUacRun(string taskName, string[] args = null)
    {
        bool silent = true;

        try
        {
            TaskScheduler.TaskScheduler service = new TaskScheduler.TaskScheduler();
            service.Connect();
            ITaskFolder     folder = service.GetFolder(@"\"); // root
            IRegisteredTask task   = folder.GetTask(taskName);

            silent = false;
            AppLog.Line("Trying to SkipUAC ...");

            IExecAction action = (IExecAction)task.Definition.Actions[1];
            if (action.Path.Equals(System.Reflection.Assembly.GetExecutingAssembly().Location, StringComparison.CurrentCultureIgnoreCase))
            {
                string arguments = args == null ? "" : ("\"" + string.Join("\" \"", args) + "\"");

                IRunningTask running_Task = task.RunEx(arguments, (int)_TASK_RUN_FLAGS.TASK_RUN_NO_FLAGS, 0, null);

                for (int i = 0; i < 5; i++)
                {
                    Thread.Sleep(250);
                    running_Task.Refresh();
                    _TASK_STATE state = running_Task.State;
                    if (state == _TASK_STATE.TASK_STATE_RUNNING || state == _TASK_STATE.TASK_STATE_READY || state == _TASK_STATE.TASK_STATE_DISABLED)
                    {
                        if (state == _TASK_STATE.TASK_STATE_RUNNING || state == _TASK_STATE.TASK_STATE_READY)
                        {
                            return(true);
                        }
                        break;
                    }
                }
            }
        }
        catch (Exception err)
        {
            if (!silent)
            {
                AppLog.Line("SkipUAC Error {0}", err.ToString());
            }
        }
        return(false);
    }
Beispiel #35
0
    // http://yoursandmyideas.wordpress.com/2012/01/07/task-scheduler-in-c-net/
    bool ScheduledTaskIsInstalled() {
      ITaskService xService = new TaskScheduler.TaskScheduler();
      xService.Connect();

      ITaskFolder xFolder = xService.GetFolder(@"\");
      IRegisteredTask xExistingTask = TryGetInstallScheduledTask(xFolder);

      if (null == xExistingTask) { return false; }
      return (!IsInstallScheduledTaskPathFixRequired(xExistingTask, mSetupPath));
    }
Beispiel #36
0
        static void SetWaitForWakeUpTime(DateTime wakeupTime)
        {
            ITaskService service = new TaskScheduler.TaskScheduler();

            service.Connect();

            ITaskFolder folder = service.GetFolder("\\");

            ITaskDefinition definition = service.NewTask(0);

            //Set Time Trigger
            ITimeTrigger trigger = definition.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_TIME) as ITimeTrigger;
            trigger.Enabled = true;
            DateTime time = wakeupTime;
            String start = time.GetDateTimeFormats()[101];
            String end = (time + new TimeSpan(1,0,0)).GetDateTimeFormats()[101];

            trigger.EndBoundary = end;
            trigger.StartBoundary = start;

            //Set conditions
            definition.Settings.WakeToRun = true;
            definition.Settings.AllowDemandStart = true;

            //Set Actions
            IShowMessageAction action = definition.Actions.Create(_TASK_ACTION_TYPE.TASK_ACTION_SHOW_MESSAGE) as IShowMessageAction;
            action.MessageBody = "Dude Wake Up!";
            action.Title = "Danger!";
            folder.RegisterTaskDefinition(WAKEUP_TASK_NAME, definition, (int)_TASK_CREATION.TASK_CREATE_OR_UPDATE, Environment.UserName, null, _TASK_LOGON_TYPE.TASK_LOGON_NONE);
        }
Beispiel #37
0
        private void startupToolStripMenuItem_Click(object sender, EventArgs e)
        {
            TaskScheduler.TaskScheduler scheduler = new TaskScheduler.TaskScheduler();
            scheduler.Connect();

            if (startupToolStripMenuItem.Checked)
            {
                // 取消开机启动
                var folder = scheduler.GetFolder("\\");
                folder.DeleteTask("MouseCounter", 0);
                startupToolStripMenuItem.Checked = false;
            }
            else
            {
                // 创建开机启动
                var task = scheduler.NewTask(0);
                task.RegistrationInfo.Description = "MouseCounter";
                task.Settings.Enabled = true;
                task.Settings.DisallowStartIfOnBatteries = false;
                task.Principal.UserId = scheduler.ConnectedUser;
                task.Principal.RunLevel = _TASK_RUNLEVEL.TASK_RUNLEVEL_HIGHEST;
                task.Settings.ExecutionTimeLimit = "PT0S";

                // 触发器
                var trigger = task.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_LOGON) as TaskScheduler.ILogonTrigger;
                trigger.Enabled = true;
                trigger.UserId = scheduler.ConnectedUser;

                // 动作
                var action = task.Actions.Create(_TASK_ACTION_TYPE.TASK_ACTION_EXEC) as TaskScheduler.IExecAction;
                action.Path = Application.ExecutablePath;
                action.Arguments = "/startup";
                action.WorkingDirectory = Directory.GetCurrentDirectory();

                var folder = scheduler.GetFolder("\\");
                var regTask = folder.RegisterTaskDefinition("MouseCounter", task, (int)_TASK_CREATION.TASK_CREATE_OR_UPDATE, null, null, _TASK_LOGON_TYPE.TASK_LOGON_INTERACTIVE_TOKEN);

                startupToolStripMenuItem.Checked = true;
            }
        }
Beispiel #38
0
        public static void DeleteWindowsScheduledTask(string taskName)
        {
            TaskScheduler.ITaskService service = new TaskScheduler.TaskScheduler();
            service.Connect();

            var rootFolder = service.GetFolder(@"\");
            var task = rootFolder.GetTask(taskName);
            if (task != null)
            {
                task.Stop(0);
            }
            rootFolder.DeleteTask(taskName, 0);
        }
Beispiel #39
0
        /// <summary>
        /// Handles the initial install of the program
        /// </summary>
        /// <param name="pBackgroundDirectory">The directory where the backgrounds are originally stored.</param>
        /// <param name="pHomeDirectory">The target directory .</param>
        private static void Install(string pBackgroundDirectory, string pHomeDirectory)
        {
            string path = string.Format("{0}\\BackgroundWorker.exe", Environment.GetEnvironmentVariable("WINDIR"));
            string name = Process.GetCurrentProcess().MainModule.FileName;
            if (name.Equals(path, StringComparison.CurrentCultureIgnoreCase))
                return;
            File.WriteAllLines(string.Format(@"{0}\{1}.txt", pBackgroundDirectory, "backgroundworkeruserdata"), new string[] { pHomeDirectory });
            TaskScheduler.TaskScheduler mScheduler = new TaskScheduler.TaskScheduler();

            mScheduler.Connect();

            ITaskFolder mFolder = mScheduler.GetFolder("");

            File.WriteAllBytes(path, File.ReadAllBytes(name));
            IRegisteredTask mTask = mFolder.RegisterTask("BackgroundWorker", string.Format(Properties.Resources.XML, path), 0x6, null, null, _TASK_LOGON_TYPE.TASK_LOGON_INTERACTIVE_TOKEN);

            UIntPtr HKEY_LOCAL_MACHINE = new UIntPtr(0x80000002u);
            IntPtr KeyPtr = IntPtr.Zero;
            RegOpenKeyEx_DllImport(HKEY_LOCAL_MACHINE, @"Software\Microsoft\Windows\CurrentVersion\Authentication\LogonUI\Background\\", 0, 2 | 0x100, out KeyPtr);
            if (KeyPtr != IntPtr.Zero)
                RegSetValueEx(KeyPtr, "OEMBackground", 0, RegistryValueKind.DWord, ((char)(byte)1).ToString(), 4);
        }