logo

得到 Windows 任务计划的列表

作者:孟宪会 阅读:298 发表于:2011-12-30 09:36:25

以下程序得到Windows任务计划列表:

C# 代码
/// <summary>
/// 需要引入 Microsoft.Win32.TaskScheduler.dll
/// 下载地址 http://taskscheduler.codeplex.com/releases/view/73297
/// using Microsoft.Win32.TaskScheduler;
public void button1_Click(object sender, EventArgs e)
{
  DataTable schedTable
= new DataTable();
  schedTable.Columns.Add(
new DataColumn("Name", typeof(string)));
  schedTable.Columns.Add(
new DataColumn("Schedule", typeof(string)));
  schedTable.Columns.Add(
new DataColumn("NextRunTime", typeof(DateTime)));
  schedTable.Columns.Add(
new DataColumn("LastRunTime", typeof(DateTime)));
  schedTable.Columns.Add(
new DataColumn("TaskState", typeof(Enum)));
  schedTable.Columns.Add(
new DataColumn("Enabled", typeof(Boolean)));
  schedTable.Columns.Add(
new DataColumn("Description", typeof(string)));

  List
<Task> tasks = new List<Task>();
  
using (TaskService ts = new TaskService())
  {
    Version ver
= ts.HighestSupportedVersion;
    
bool newVer = (ver >= new Version(1, 2));      
    TaskFolder tf
= ts.RootFolder;
    
// 得到目录下的所有任务计划
    foreach (Task t in tf.Tasks)
    {
      tasks.Add(t);
      
string trStr = "";
      DataRow r
= schedTable.NewRow();
      
try
      {
        
this.textBox1.AppendText(t.Name + Environment.NewLine);
        r[
"Name"] = t.Name;
        
foreach (Trigger tr in t.Definition.Triggers)
        {
          
if (trStr != "")
            trStr
+= ";";
          trStr
+= tr.ToString();
        }
        r[
"Schedule"] = trStr;
        r[
"NextRunTime"] = t.NextRunTime;
        r[
"LastRunTime"] = t.LastRunTime;
        r[
"TaskState"] = t.State;
        r[
"Enabled"] = t.Enabled;
        r[
"Description"] = t.Definition.RegistrationInfo.Description;
        schedTable.Rows.Add(r);
      }
      
catch { }
    }
  }
}