Advertisement
KiberInfinity

MsTask

Nov 23rd, 2015
153
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. Hi,
  2.  
  3. As said in my previous post, here is a complete fully functional demo showing how to create a scheduled task(in the example launch the calc.exe) with the MSTask.pas unit. See how the procedure of eah button are implemented to perform each task.
  4.  
  5. __________________ paste code below and save as Unit1.pas __________________________
  6. Unit 1
  7.  
  8. unit Unit1;
  9.  
  10. interface
  11.  
  12. uses
  13.   Windows, Messages, SysUtils, Classes, Graphics,
  14.   Controls, Forms, Dialogs,
  15.   ActiveX, ImgList, MsTask, MsTaskUtils, Menus,
  16.   Shellapi, StdCtrls, ExtCtrls, ComCtrls;
  17.  
  18. type
  19.   TForm1 = class(TForm)
  20.     Label1: TLabel;
  21.     ListandCountTasks: TButton;
  22.     Memo1: TMemo;
  23.     SchedAgentEnum: TButton;
  24.     GetTargetPC: TButton;
  25.     ListBox1: TListBox;
  26.     LoadTasks: TButton;
  27.     ImageList1: TImageList;
  28.     Image1: TImage;
  29.     FileNameOfSelTask: TButton;
  30.     RunSelectTask: TButton;
  31.     TaskStatut: TButton;
  32.     SeeParam: TButton;
  33.     SeePrior: TButton;
  34.     WorkDTaskFlags: TButton;
  35.     Button12: TButton;
  36.     ApplicTask: TButton;
  37.     Planification: TButton;
  38.     SetTaskAccount: TButton;
  39.     Label2: TLabel;
  40.     RichEdit1: TRichEdit;
  41.     procedure FormCreate(Sender: TObject);
  42.     procedure ListandCountTasksClick(Sender: TObject);
  43.     procedure SchedAgentEnumClick(Sender: TObject);
  44.     procedure GetTargetPCClick(Sender: TObject);
  45.     procedure LoadTasksClick(Sender: TObject);
  46.     procedure ListBox1Click(Sender: TObject);
  47.     procedure RunSelectTaskClick(Sender: TObject);
  48.     procedure TaskStatutClick(Sender: TObject);
  49.     procedure SeeParamClick(Sender: TObject);
  50.     procedure SeePriorClick(Sender: TObject);
  51.     procedure WorkDTaskFlagsClick(Sender: TObject);
  52.     procedure Button12Click(Sender: TObject);
  53.     procedure ApplicTaskClick(Sender: TObject);
  54.     procedure PlanificationClick(Sender: TObject);
  55.     procedure SetTaskAccountClick(Sender: TObject);
  56.     procedure FileNameOfSelTaskClick(Sender: TObject);
  57.   private
  58.     { Déclarations privées }
  59.     Function Init(Lbl:TLabel): HRESULT;
  60.  
  61.   public
  62.     { Déclarations publiques }
  63.   end;
  64.  
  65. var
  66.   Form1: TForm1;
  67.   SchedulingAgent: ITaskScheduler;
  68.   ScheduledWorkItem: IScheduledWorkItem;
  69.   pIPersistFile: IPersistFile;
  70.   Task: ITask;
  71.  
  72.   MyComputerName,
  73.   MyAppname,
  74.   MyParameters,
  75.   MyWorkingDir,
  76.   MyTaskFlags : String;
  77.  
  78.   implementation
  79.  
  80. uses AuxProcs;
  81.  
  82. {$R *.DFM}
  83.  
  84. ///////////////////////////////////////////////////////////
  85.  
  86. Function TForm1.Init(Lbl:TLabel): HRESULT;
  87. begin
  88.   Result := S_OK;
  89.   Lbl.Caption:= '';
  90.   if not assigned(SchedulingAgent) then
  91.   begin
  92.     Result := ActiveX.CoInitialize(nil);
  93.     if Result <> S_OK then
  94.     begin
  95.       ActiveX.CoUninitialize;
  96.       Lbl.caption:= 'Error in ActiveX.CoInitialize. Error Code: ' + IntToHex(Result, 8);
  97.       Application.Terminate;
  98.     end else
  99.     Lbl.Caption:= 'OK with ActiveX.CoInitialize';
  100.  
  101.     Result := ActiveX.CoCreateInstance(
  102.        CLSID_CSchedulingAgent,
  103.        nil,
  104.        CLSCTX_INPROC_SERVER,
  105.        IID_ITaskScheduler,
  106.        SchedulingAgent);
  107.  
  108.     if Result <> S_OK then
  109.     begin
  110.     Lbl.caption:= 'Error in ActiveX.CoCreateInstance. Error Code: ' + IntToHex(Result, 8);
  111.     Application.Terminate;
  112.     end;
  113.   end;
  114. end;
  115.  
  116. ///////////////////////////////////////////////////////////
  117.  
  118. Function GetITask(TaskName: string;Lbl:TLabel): ITask;
  119. var
  120.   PITask: IUnknown;
  121.   hr: HRESULT;
  122. begin
  123.   Lbl.caption:= '';
  124.   hr := SchedulingAgent.Activate(AuxProcs.StrToWide(TaskName), IID_ITask, PITask);
  125.   if hr = S_OK then
  126.   Result := ITask(PITask)
  127.   else
  128.   begin
  129.     Lbl.Caption:= 'Error in SchedulingAgent.Activate. Error Code: ' + IntToHex(hr, 8);
  130.     Result := nil;
  131.   end;
  132. end;
  133.  
  134. ///////////////////////////////////////////////////////////
  135.  
  136. Function SaveTask(Lbl:TLabel): HRESULT;
  137. begin
  138.   Result := -1;
  139.   Task.QueryInterface(IID_IPersistFile, pIPersistFile);
  140.   if pIPersistFile <> nil then
  141.   begin
  142.     Result := pIPersistFile.Save(nil, true);
  143.   end
  144.   else
  145.   Lbl.caption:= 'Error in Task.QueryInterface(IID_IPersistFile, pIPersistFile): ';
  146. end;
  147.  
  148. ///////////////////////////////////////////////////////////
  149.  
  150. Function DeleteTask(JobName: string): HRESULT;
  151. begin
  152.   Result := SchedulingAgent.Delete(StrToWide(JobName));
  153. end;
  154.  
  155. ///////////////////////////////////////////////////////////
  156.  
  157. Procedure IsOkScheduler(Lbl: TLabel);
  158. var
  159.   hr: HRESULT;
  160. begin
  161.   Lbl.Caption:= '';
  162.   hr := StartScheduler;
  163.   if hr = ERROR_SUCCESS then
  164.   Lbl.Caption:= 'Task Scheduler has started successfully.'
  165.   else
  166.   Lbl.Caption := 'Task Scheduler didn''t start. Error Code:' + IntTohex(hr, 8);
  167. end;
  168.  
  169. ///////////////////////////////////////////////////////////
  170. procedure SetTargetComputer(Txt:TMemo);
  171. var
  172.   hr: HResult;
  173.   ComputerName: PWideChar;
  174. begin
  175. //$80070035 networkpath not found
  176. //$80070005 General access denied
  177. //passing nil as computername should return local machine target computer
  178.   ComputerNAme := StrToWide(MyComputerName);
  179.   Txt.Lines.Add('Trying to set Target Computername to:' + MyComputerName);
  180.   hr := SchedulingAgent.SetTargetComputer(ComputerName);
  181.   if hr = S_OK then
  182.   Txt.Lines.Add('Target Computername is set to:' + WideCharToString(ComputerNAme))
  183.   else
  184.   begin
  185.     if hr = SCHED_E_SERVICE_NOT_INSTALLED then
  186.     Txt.Lines.Add('TargetComputer does not have service installed');
  187.     Txt.Lines.Add('SetTargetComputer failed with error code:$' + IntTohex(hr, 8));
  188.   end;
  189. end;
  190. //-----------------------------------------------------------
  191. procedure TForm1.FormCreate(Sender: TObject);
  192. begin
  193. IsOkScheduler(Label1);
  194. LoadTasksClick(self);
  195. end;
  196. //-----------------------------------------------------------
  197. procedure TForm1.SchedAgentEnumClick(Sender: TObject);
  198. var
  199.   hr: HRESULT;
  200.   pEnum: IEnumWorkItems;
  201. begin
  202. Memo1.clear;
  203. Init(Label2);
  204. hr := SchedulingAgent.Enum(pEnum);
  205.    if hr <> S_OK then
  206.    Memo1.Lines.Add('SchedulingAgent.Enum Result:' + IntTohex(hr, 8))
  207.    else
  208.    Memo1.Lines.Add('SchedulingAgent.Enum Result: OK');
  209. end;
  210. //-----------------------------------------------------------
  211. procedure TForm1.GetTargetPCClick(Sender: TObject);
  212. var
  213.   ComputerName: PWideChar;
  214.   hr: HResult;
  215. begin
  216. Memo1.clear;
  217. Init(Label2);
  218. hr := SchedulingAgent.GetTargetComputer(ComputerName);
  219. if hr = S_OK then
  220.   begin
  221.   Memo1.Lines.Add('Target Computername is :' + WideCharToString(ComputerNAme) + #13#10);
  222.   MyComputerName := WideCharToString(ComputerNAme);
  223.   end
  224.   else
  225.   Memo1.Lines.Add('GetTargetComputer failed with error code :$' + IntTohex(hr, 8) + #13#10);
  226. end;
  227. //-----------------------------------------------------------
  228. procedure TForm1.ListandCountTasksClick(Sender: TObject);
  229. var
  230. hr: HRESULT;
  231. pEnum: IEnumWorkItems;
  232. TaskNames: PLPWSTR;
  233. dwFetched: DWORD;
  234. szString: string;
  235. Appname: PWideChar;
  236. begin
  237. Memo1.clear;
  238. Listbox1.clear;
  239. GetTargetPCClick(self);
  240. hr := SchedulingAgent.Enum(pEnum);
  241. while (pEnum.Next(1, TaskNames, dwFetched) = 0) and (dwFetched > 0) do
  242.   begin
  243.   szString := WideCharToString(TaskNames^);
  244.   Memo1.Lines.Add('Enum.Next fetched: ' + IntToStr(dwFetched) + ' item(s).');
  245.   Memo1.Lines.Add('Taskname: ' + szString);
  246.   Memo1.Lines.Add('---------------------');
  247.   ListBox1.Items.Add(szString);
  248.   ActiveX.CoTaskMemFree(TaskNames);
  249.   end;
  250. end;
  251. //-----------------------------------------------------------
  252. procedure TForm1.FileNameOfSelTaskClick(Sender: TObject);
  253. var
  254. i: integer;
  255. Appname: PWideChar;
  256. begin
  257. Memo1.clear;
  258.  for i:= 0 to ListBox1.items.count -1 do
  259.  begin
  260.    if listbox1.Selected[i] then
  261.       begin
  262.       Memo1.clear;
  263.       Task := GetITask(ListBox1.Items[ListBox1.Itemindex],label2);
  264.       Task.GetApplicationName(Appname);
  265.       Memo1.lines.Add('The task  : ' + ListBox1.Items[ListBox1.Itemindex]);
  266.       Memo1.lines.Add('Call the following application file: ');
  267.       Memo1.lines.Add(AppName);
  268.       end;
  269.  end;
  270. end;
  271. //-----------------------------------------------------------
  272. procedure TForm1.LoadTasksClick(Sender: TObject);
  273. var
  274.   hr: HRESULT;
  275.   pEnum: IEnumWorkItems;
  276.   TaskNames: PLPWSTR;
  277.   dwFetched: DWORD;
  278.   szString: string;
  279.   TriggCount: Word;
  280.   Appname: PWideChar;
  281.   IconIndex: Word;
  282.   Icon: TIcon;
  283.   TriggStr: PwideChar;
  284.   NextRunTime: _SYSTEMTIME;
  285. begin
  286. Memo1.clear;
  287. Listbox1.Clear;
  288.  
  289. Icon := TIcon.Create;
  290. IconIndex := 0;
  291.  
  292. GetTargetPCClick(self);
  293. Init(label2);
  294. hr := SchedulingAgent.Enum(pEnum);
  295.  
  296. ImageList1.Clear;
  297.  
  298. while (pEnum.Next(1, TaskNames, dwFetched) = 0) and (dwFetched > 0) do
  299.   begin
  300.  
  301. //Taskname from enum
  302.     szString := WideCharToString(TaskNames^);
  303.     Memo1.lines.Add(szString);
  304.     ListBox1.Items.Add(szString);  // add the name of each existing task
  305. //for getting the icon from filename of task
  306.     Task := GetITask(szString,label2);
  307.     Task.GetApplicationName(Appname);
  308.  
  309.     if MyComputerName = '\\' + GetLocalComputerName then
  310.     begin
  311.     Memo1.lines.Add('Name of application: '+(PChar(WideCharToString(Appname))));
  312.     Icon.Handle := ExtractAssociatedIcon(Hinstance, PChar(WideCharToString(Appname)), IconIndex);
  313.     Image1.Picture.Icon:= Icon;
  314.     end;
  315.  
  316.     Task.GetWorkingDirectory(Appname);
  317.     Memo1.lines.Add('GetWorkingDir: '+WideCharToString(Appname));
  318.  
  319. //GetStatus
  320.     Task.GetStatus(hr);
  321.     Memo1.lines.Add(MessageFromValue(hr));
  322. //GetNextRecentTime
  323.     hr := Task.GetNextRunTime(NextRunTime);
  324.     if hr = S_OK then
  325.     Memo1.lines.Add('NextRunTime: '+ DateTimeToStr(SystemTimeToDateTime(NextRunTime)))
  326.     else
  327.     Memo1.lines.Add('Next RunTime'+ MessageFromValue(hr)); ;
  328. //GetMostRecentTime
  329.     hr := Task.GetMostRecentRunTime(NextRunTime);
  330.     if hr = S_OK then
  331.     Memo1.lines.Add('Recent runtime: ' + DateTimeToStr(SystemTimeToDateTime(NextRunTime)))
  332.     else
  333.     Memo1.lines.Add('Recent runtime: ' +  MessageFromValue(hr)); ;
  334. //GetTriggerString and GetTriggerCount
  335.     hr := Task.GetTriggerCount(TriggCount);
  336.     if hr = S_OK then
  337.       if TriggCount > 1 then
  338.       begin
  339.         Memo1.lines.Add('Multiple schedule times');
  340.       end
  341.       else
  342.       begin
  343.         Task.GetTriggerString(0, TriggStr);
  344.         if TriggStr <> nil then
  345.         Memo1.lines.Add('Planification: ' + WideCharToString(TriggStr));
  346.  
  347.       end;
  348.               Memo1.lines.Add('');
  349.       ActiveX.CoTaskMemFree(TaskNames);
  350.   end;
  351. Icon.free;
  352. end;
  353. //-----------------------------------------------------------
  354. procedure TForm1.TaskStatutClick(Sender: TObject);
  355. var
  356.   hr: HRESULT;
  357.   i: integer;
  358. begin
  359. Memo1.clear;
  360.  for i:= 0 to ListBox1.items.count -1 do
  361.  begin
  362.    if listbox1.Selected[i] then
  363.       begin
  364.       Task := GetITask(Listbox1.Items[i],label2);
  365.       Task.GetStatus(hr);
  366.       Memo1.Lines.Add('GetStatus returned value :' + IntToHex(hr, 8));
  367.       Memo1.Lines.Add('Message from value : ' +  MessageFromValue(hr));
  368.       end;
  369.   end;
  370. end;
  371. //-----------------------------------------------------------
  372. procedure TForm1.SeeParamClick(Sender: TObject);
  373. var
  374. i: integer;
  375. pParameters: PWideChar;
  376. begin
  377. Memo1.clear;
  378. for i:= 0 to ListBox1.items.count -1 do
  379. begin
  380.    if listbox1.Selected[i] then
  381.       begin
  382.       Task := GetITask(Listbox1.Items[i],label2);
  383.       Task.GetParameters(pParameters);
  384.          if WideCharToString(pParameters) = '' then
  385.          Memo1.Lines.Add('GetParameters did not return any value as there are no parameters' + #13#10)
  386.          else
  387.          Memo1.Lines.Add('GetParameters returned :' + WideCharToString(pParameters) + #13#10);
  388.          MyParameters := WideCharToString(pParameters);
  389.       end;
  390.   end;
  391. end;
  392. //-----------------------------------------------------------
  393. procedure TForm1.SeePriorClick(Sender: TObject);
  394. var
  395. i: integer;
  396. Priority: Cardinal;
  397. PriorityStr: string;
  398. begin
  399. Memo1.clear;
  400. for i:= 0 to ListBox1.items.count -1 do
  401. begin
  402.  if listbox1.Selected[i] then
  403.       begin
  404.       Task := GetITask(Listbox1.Items[i],label2);
  405.       Task.GetPriority(Priority);
  406.       case Priority of
  407.            REALTIME_PRIORITY_CLASS: PriorityStr := 'Realtime';
  408.            HIGH_PRIORITY_CLASS: PriorityStr := 'High';
  409.            NORMAL_PRIORITY_CLASS: PriorityStr := 'Normal';
  410.            IDLE_PRIORITY_CLASS: PriorityStr := 'Idle';
  411.       end;
  412.       Memo1.Lines.Add('The priority of the task is ' + PriorityStr + #13#10);
  413.       end;
  414.  end;
  415. end;
  416. //-----------------------------------------------------------
  417. procedure TForm1.WorkDTaskFlagsClick(Sender: TObject);
  418. var
  419. //Appname: PWideChar;
  420. i: integer;
  421. pWorkingDir: PWideChar;
  422. PdwFlags: Cardinal;
  423. begin
  424.  
  425. for i:= 0 to ListBox1.items.count -1 do
  426. begin
  427.    if listbox1.Selected[i] then
  428.       begin
  429.       Memo1.clear;
  430.       Task.GetWorkingDirectory(pWorkingDir);
  431.       if WideCharToString(pWorkingDir) = '' then
  432.          Memo1.Lines.Add('GetWorkingDirectory did not return any value as there are no parameters')
  433.          else
  434.          Memo1.Lines.Add('GetWorkingDirectory returned: ' + WideCharToString(pWorkingDir));
  435.          MyWorkingDir := WideCharToString(pWorkingDir);
  436.  
  437.          Task.GetTaskFlags(PdwFlags);
  438.          Memo1.Lines.Add('GetTask Flags returned value of PdwFlags ' + IntToStr(PdwFlags));
  439.          MyTaskFlags := IntToStr(PdwFlags);
  440.          end;
  441.      end;
  442. end;
  443. //-----------------------------------------------------------
  444. procedure TForm1.ListBox1Click(Sender: TObject);
  445. //var
  446. //  Appname: PWideChar;
  447. //  szString: string;
  448. //  IconIndex: Word;
  449. //  Icon: TIcon;
  450. //  i: integer;
  451. begin
  452. //Memo1.clear;
  453. // for i:= 0 to ListBox1.items.count -1 do
  454. // begin
  455. //
  456. //   if listbox1.Selected[i] then
  457. //      begin
  458. //      Memo1.clear;
  459. //      Task := GetITask(ListBox1.Items[ListBox1.Itemindex],label2);
  460. //      Task.GetApplicationName(Appname);
  461. //      Memo1.Lines.Add('Application Name is: ' + WideCharToString(Appname));
  462. //      MyAppname:= WideCharToString(Appname);
  463. //
  464. //      Icon := TIcon.Create;
  465. //      IconIndex := 0;
  466. //
  467. //    if MyComputerName = '\\' + GetLocalComputerName then
  468. //    begin
  469. //    Memo1.lines.Add('Name of application: '+(PChar(WideCharToString(Appname))));
  470. //    Icon.Handle := ExtractAssociatedIcon(Hinstance, PChar(WideCharToString(Appname)), IconIndex);
  471. //    Image1.Picture.Icon:= Icon;
  472. //    end;
  473. //    Icon.free;
  474. //    end;
  475. //end;
  476. end;
  477. //-----------------------------------------------------------
  478. procedure TForm1.ApplicTaskClick(Sender: TObject);
  479. var
  480. Priority: Cardinal;
  481. PriorityStr: string;
  482. hr: HRESULT;
  483. Idx : integer;
  484. begin
  485. Memo1.clear;
  486. Idx:= ListBox1.Itemindex;
  487.  
  488. Task := GetITask(Listbox1.Items[idx],label2);
  489. MyAppName:= 'Calc.exe';
  490. HR := Task.SetApplicationName(StrToWide(MyAppname));
  491.  
  492. if HR = S_OK then
  493. Memo1.Lines.Add('Application Name is set to :' + MyAppname)
  494. else
  495. begin
  496. Memo1.Lines.Add('Error in setting Application Name to :' + MyAppname + 'Error Code:' + IntTohex(HR, 8));
  497. Exit;
  498. end;
  499.  
  500. SaveTAsk(Label2);
  501. end;
  502. //-----------------------------------------------------------
  503. procedure TForm1.SetTaskAccountClick(Sender: TObject);
  504. var
  505. i: integer;
  506. Username, Password: string;
  507. hr: HRESULT;
  508. uname, pass: PWideChar;
  509. PdwFlags: Cardinal;
  510.  
  511. begin
  512. Memo1.clear;
  513.  
  514.  if ListBox1.items.count -1 > 0 then
  515.  begin
  516.    for i:= 0 to Listbox1.Items.count - 1 do
  517.    if listbox1.Selected[i] then
  518.       begin
  519.  
  520.       Username := 'Bernard';
  521.       Password := '';
  522.       GetMem(uname, 255);
  523.       GetMem(pass, 255);
  524.       StringToWideChar(Username, uname, Length(UserName) + 1);
  525.       StringToWideChar(Password, pass, Length(Password) + 1);
  526.  
  527.   Task := GetITask(Listbox1.Items[i],label2);
  528.   Task.SetFlags(8192);
  529.   hr := Task.SetAccountInformation(uname, pass);
  530.   SaveTask(Label2);
  531. LoadTasksClick(Self);
  532.   case hr of
  533.     S_OK:
  534.     begin
  535.     Memo1.Lines.Add('SetAccountInformation success');
  536.     end;
  537.     E_ACCESSDENIED: Memo1.Lines.Add('The caller does not have permission to perform the operation. For more information, see Remarks.');
  538.     E_INVALIDARG: Memo1.Lines.Add('The arguments are not valid.');
  539.     E_OUTOFMEMORY: Memo1.Lines.Add('Not enough memory is available.');
  540.     else
  541.     begin
  542.     Memo1.Lines.Add(MessageFromValue(hr));
  543.     Memo1.Lines.Add('SetAccountInformation failed with errorcode :' + IntTohex(hr, 8) + #13#10);
  544.     end;
  545.   end;
  546.   FreeMem(uname);
  547.   FreeMem(pass);
  548.   HR := Task.SetTaskFlags(StrToInt('$2000'));
  549.  
  550.   if HR = S_OK then Memo1.Lines.Add('SetTaskFlags set to :' + myTaskFlags)
  551.   else
  552.   begin
  553.   Memo1.Lines.Add('Error in setting flags to :' + MyTaskFlags + 'Error Code:' + IntTohex(HR, 8));
  554.   exit;
  555.   end;
  556.  
  557.   if hr <> S_OK then
  558.   Memo1.lines.add('Save task failed with error code' + IntTohex(hr, 8) + #13#10);
  559.       end;
  560. Task.Run;
  561. // Uncomment line under to see the windows dialog sched.
  562. //Task.EditWorkItem(self.handle,0);
  563.  end;
  564. end;
  565. //-----------------------------------------------------------
  566. procedure TForm1.RunSelectTaskClick(Sender: TObject);
  567. var
  568.   hr: HRESULT;
  569.   i: integer;
  570. begin
  571.  for i:= 0 to ListBox1.items.count -1 do
  572.  begin
  573.  
  574.    if listbox1.Selected[i] then
  575.       begin
  576.       Task := GetITask(Listbox1.Items[i],label2);
  577.       HR := Task.SetTaskFlags(StrToInt('$2000'));//MyTaskFlags));
  578.       hr := Task.Run;
  579.       Memo1.Lines.Add('Run Application Error Code :' + IntTohex(hr, 8) + #13#10);
  580.       Memo1.Lines.Add(MyAppName);//Listbox1.Items[i]);
  581.       //  BtnGetTasksClick(self); //for updating
  582.       end;
  583.   end;
  584. end;
  585. //-----------------------------------------------------------
  586. procedure TForm1.Button12Click(Sender: TObject);
  587. var
  588.   Appname: PWideChar;
  589.   szString: string;
  590.   IconIndex: Word;
  591.   Icon: TIcon;
  592.   i: integer;
  593.   pWorkingDir: PWideChar;
  594.   PdwFlags: Cardinal;
  595. //
  596.   HR : HRESULT;
  597.   TaskName: string;
  598.   WorkItem: IUnknown;
  599.     Creator: PWideChar;
  600.     MaxRunTime: DWORD;
  601. begin
  602. Memo1.clear;
  603. TaskName := '001000'; // name of the task - here hardcoded
  604. Init(Label2);
  605.  
  606. HR := SchedulingAgent.NewWorkItem(
  607.            StrToWide(TaskName),
  608.            CLSID_CTask,
  609.            IID_IScheduledWorkItem,
  610.            WorkItem);
  611.  
  612. Task := ITask(WorkItem); //required for save
  613. ScheduledWorkItem := IScheduledWorkItem(WorkItem);
  614.  
  615. if HR = S_OK then
  616. begin
  617. Listbox1.items.add(Taskname);
  618. Memo1.Lines.Add(Taskname + ' created successfully');
  619. Listbox1.Update;
  620. end
  621. else
  622. begin
  623. Memo1.Lines.Add('Could not create the job ' + taskname + '. Error Code: ' + IntTohex(hr, 8));
  624. exit;
  625. end;
  626.  
  627. hr := SaveTAsk(Label2);
  628.  
  629. if hr <> S_OK then Memo1.lines.add('Save task failed with error code: ' + IntTohex(hr, 8));
  630.  
  631.  
  632. Memo1.clear;
  633.  
  634. Task := GetITask(Taskname,label2);
  635. Task.GetApplicationName(Appname);
  636. Memo1.Lines.Add('Application Name is: ' + WideCharToString(Appname));
  637. MyAppname:= WideCharToString(Appname);
  638.  
  639.    Icon := TIcon.Create;
  640.    IconIndex := 0;
  641.  
  642.     if MyComputerName = '\\' + GetLocalComputerName then
  643.     begin
  644.     Memo1.lines.Add('Name of application: '+(PChar(WideCharToString(Appname))));
  645.     Icon.Handle := ExtractAssociatedIcon(Hinstance, PChar(WideCharToString(Appname)), IconIndex);
  646.     Image1.Picture.Icon:= Icon;
  647.  
  648.     Task := GetITask(TaskName,label2);
  649.     Task.GetCreator(Creator);
  650.     Memo1.Lines.Add('The Name of the Creator of the selected job is : ' + WideCharToString(Creator));
  651.  
  652.     Task := GetITask(Taskname,label2);
  653.     Task.GetMaxRunTime(MaxRunTime);
  654.     Memo1.Lines.Add('GetMaxRunTime returned: ' + IntToStr(MaxRunTime) + ' milliseconds');
  655.     end;
  656.  
  657.     Icon.free;
  658. //    end;
  659.  
  660. end;
  661. //-----------------------------------------------------------
  662. procedure TForm1.PlanificationClick(Sender: TObject);
  663. var
  664. i: integer;
  665.   hr: HRESULT;
  666.   piNewTrigger: Word;
  667.   ITTrigger: ITaskTrigger;
  668.   TaskTrig: TTaskTRIGGER;
  669.   Count: Word;
  670. begin
  671. memo1.clear;
  672.  for i:= 0 to ListBox1.items.count -1 do
  673.  begin
  674.    if listbox1.Selected[i] then
  675.       begin
  676.       Task := GetITask(Listbox1.Items[i],label2);
  677.       HR := Task.CreateTrigger(piNewTrigger, ITTrigger);
  678.  
  679.       if HR = S_OK then
  680.       Memo1.Lines.Add('Create Trigger success ')
  681.       else
  682.       begin
  683.       Memo1.Lines.Add('Error in Create Trigger Error Code:' + IntToHex(HR, 8));
  684.       exit;
  685.       end;
  686.  
  687.       ZeroMemory(@TaskTrig, sizeof(TASK_TRIGGER));
  688.       TaskTrig.cbTriggerSize := sizeof(TASK_TRIGGER);
  689.       TaskTrig.Reserved1 := 0;
  690.       TaskTrig.wBeginYear := 2006;
  691.       TaskTrig.wBeginMonth := 11;
  692.       TaskTrig.wBeginDay := 27;
  693.       TaskTrig.wEndYear := 2006;
  694.       TaskTrig.wEndMonth := 11;
  695.       TaskTrig.wEndDay := 30;
  696.       TaskTrig.wStartHour := 16;
  697.       TaskTrig.wStartMinute := 25;
  698.       TaskTrig.MinutesDuration := 0;
  699.       TaskTrig.MinutesInterval := 0;
  700.       TaskTrig.rgFlags := 0;
  701. {rgFlags
  702. Value that describes the task trigger's behavior.
  703. This value is a combination of the following flags:
  704. TASK_TRIGGER_FLAG_HAS_END_DATE
  705. Trigger structure's end date is valid.
  706. If this flag is not set, the end date data is ignored and
  707. the trigger will be valid indefinitely.
  708.  
  709. TASK_TRIGGER_FLAG_KILL_AT_DURATION_END
  710. Task will be terminated at the end of the active trigger's
  711. lifetime. At the duration end, the scheduling agent
  712. first sends a WM_CLOSE message to
  713. the associated application. If the application hasn't
  714. exited in three minutes,TerminateProcess runs.
  715. If more than one instance of a task is running,
  716. all instances are terminated.
  717.  
  718. TASK_TRIGGER_FLAG_DISABLED
  719. Task trigger is inactive.
  720. }
  721.  
  722.   TaskTrig.TriggerType := TASK_TIME_TRIGGER_ONCE;
  723.   TaskTrig.wRandomMinutesInterval := 0;
  724.   TaskTrig.Reserved2 := 0;
  725.  
  726.   hr := ITTrigger.SetTrigger(@TaskTrig);
  727.   if (hr <> S_OK) then
  728.   begin
  729.     Memo1.Lines.Add(MessageFromValue(hr));
  730.     exit;
  731.   end;
  732.     SaveTAsk(Label2);
  733.   end;
  734.  
  735.   end; {for}
  736.  
  737. //display properties of trigger
  738.   try Task.GetTriggerCount(Count)except {} end;
  739.   if Count <= 0 then
  740.   begin
  741.     ShowMessage('No triggers');
  742.     Exit;
  743.   end;
  744.  
  745.   Task.GetTrigger(0, ITTrigger);
  746.   TaskTrig.cbTriggerSize := sizeof(TASK_TRIGGER);
  747.  
  748.   hr := ITTrigger.GetTrigger(@TaskTrig);
  749.   if (hr <> S_OK) then
  750.   begin
  751.   Memo1.clear;
  752.   Memo1.Lines.Add(MessageFromValue(hr));
  753.   exit;
  754.   end;
  755.   Memo1.Lines.Add('Get Trigger Returned :');
  756.   Memo1.Lines.Add(' Begin Year:' + IntToStr(TaskTrig.wBeginYear) + #13#10 +
  757.     ' Begin Month:' + IntToStr(TaskTrig.wBeginMonth) + #13#10 +
  758.     ' Begin Day:' + IntToStr(TaskTrig.wBeginDay) + #13#10 +
  759.     ' End Year:' + IntToStr(TaskTrig.wEndYear) + #13#10 +
  760.     ' End Month:' + IntToStr(TaskTrig.wEndMonth) + #13#10 +
  761.     ' End Day:' + IntToStr(TaskTrig.wEndDay));
  762. end; {proc}
  763.  
  764. end.
  765.  
  766. __________________ paste code below and save as Projec1.dpr __________________________
  767. program Project1;
  768.  
  769. uses
  770.   Forms,
  771.   Unit1 in 'Unit1.pas' {Form1},
  772.   AuxProcs in 'AuxProcs.pas',
  773.   MsTaskUtils in 'MsTaskUtils.pas';
  774.  
  775. {$R *.RES}
  776.  
  777. begin
  778.   Application.Initialize;
  779.   Application.CreateForm(TForm1, Form1);
  780.   Application.Run;
  781. end.
  782.  
  783. __________________ paste code below and save as Unit1.dfm __________________________
  784. object Form1: TForm1
  785.   Left = 243
  786.   Top = 105
  787.   Width = 696
  788.   Height = 601
  789.   Caption = 'Creating a scheduled task under Delphi ...'
  790.   Color = clWhite
  791.   Font.Charset = DEFAULT_CHARSET
  792.   Font.Color = clWindowText
  793.   Font.Height = -11
  794.   Font.Name = 'MS Shell Dlg 2'
  795.   Font.Style = []
  796.   OldCreateOrder = False
  797.   ShowHint = True
  798.   OnCreate = FormCreate
  799.   PixelsPerInch = 96
  800.   TextHeight = 13
  801.   object Label1: TLabel
  802.     Left = 19
  803.     Top = 16
  804.     Width = 331
  805.     Height = 13
  806.     AutoSize = False
  807.     Color = clBlue
  808.     Font.Charset = DEFAULT_CHARSET
  809.     Font.Color = clWhite
  810.     Font.Height = -11
  811.     Font.Name = 'MS Shell Dlg 2'
  812.     Font.Style = [fsBold]
  813.     ParentColor = False
  814.     ParentFont = False
  815.   end
  816.   object Image1: TImage
  817.     Left = 72
  818.     Top = 483
  819.     Width = 57
  820.     Height = 46
  821.     Center = True
  822.   end
  823.   object Label2: TLabel
  824.     Left = 359
  825.     Top = 16
  826.     Width = 304
  827.     Height = 13
  828.     AutoSize = False
  829.     Color = clYellow
  830.     Font.Charset = DEFAULT_CHARSET
  831.     Font.Color = clRed
  832.     Font.Height = -11
  833.     Font.Name = 'MS Shell Dlg 2'
  834.     Font.Style = [fsBold]
  835.     ParentColor = False
  836.     ParentFont = False
  837.   end
  838.   object ListandCountTasks: TButton
  839.     Left = 14
  840.     Top = 105
  841.     Width = 169
  842.     Height = 25
  843.     Caption = 'ListandCountTasks'
  844.     TabOrder = 0
  845.     OnClick = ListandCountTasksClick
  846.   end
  847.   object Memo1: TMemo
  848.     Left = 360
  849.     Top = 48
  850.     Width = 303
  851.     Height = 281
  852.     ScrollBars = ssVertical
  853.     TabOrder = 1
  854.   end
  855.   object SchedAgentEnum: TButton
  856.     Left = 14
  857.     Top = 45
  858.     Width = 169
  859.     Height = 25
  860.     Caption = 'SchedulingAgent.Enum'
  861.     TabOrder = 2
  862.     OnClick = SchedAgentEnumClick
  863.   end
  864.   object GetTargetPC: TButton
  865.     Left = 14
  866.     Top = 75
  867.     Width = 169
  868.     Height = 25
  869.     Caption = 'GetTargetComputer'
  870.     TabOrder = 3
  871.     OnClick = GetTargetPCClick
  872.   end
  873.   object ListBox1: TListBox
  874.     Left = 192
  875.     Top = 48
  876.     Width = 161
  877.     Height = 497
  878.     Color = 16731983
  879.     Columns = 1
  880.     Font.Charset = DEFAULT_CHARSET
  881.     Font.Color = clWhite
  882.     Font.Height = -11
  883.     Font.Name = 'MS Shell Dlg 2'
  884.     Font.Style = [fsBold]
  885.     ItemHeight = 13
  886.     ParentFont = False
  887.     TabOrder = 4
  888.     OnClick = ListBox1Click
  889.   end
  890.   object LoadTasks: TButton
  891.     Left = 14
  892.     Top = 134
  893.     Width = 169
  894.     Height = 25
  895.     Caption = 'Load task and infos'
  896.     Font.Charset = DEFAULT_CHARSET
  897.     Font.Color = clRed
  898.     Font.Height = -11
  899.     Font.Name = 'MS Shell Dlg 2'
  900.     Font.Style = [fsBold]
  901.     ParentFont = False
  902.     TabOrder = 5
  903.     OnClick = LoadTasksClick
  904.   end
  905.   object FileNameOfSelTask: TButton
  906.     Left = 14
  907.     Top = 164
  908.     Width = 169
  909.     Height = 25
  910.     Hint = 'Select job and click '
  911.     Caption = 'Applic. name of selected task'
  912.     TabOrder = 6
  913.     OnClick = FileNameOfSelTaskClick
  914.   end
  915.   object RunSelectTask: TButton
  916.     Left = 14
  917.     Top = 432
  918.     Width = 169
  919.     Height = 25
  920.     Caption = 'Run application'
  921.     TabOrder = 7
  922.     OnClick = RunSelectTaskClick
  923.   end
  924.   object TaskStatut: TButton
  925.     Left = 14
  926.     Top = 194
  927.     Width = 169
  928.     Height = 25
  929.     Caption = 'Statut of theTask'
  930.     TabOrder = 8
  931.     OnClick = TaskStatutClick
  932.   end
  933.   object SeeParam: TButton
  934.     Left = 14
  935.     Top = 224
  936.     Width = 169
  937.     Height = 25
  938.     Caption = 'See Parameters'
  939.     TabOrder = 9
  940.     OnClick = SeeParamClick
  941.   end
  942.   object SeePrior: TButton
  943.     Left = 14
  944.     Top = 254
  945.     Width = 169
  946.     Height = 25
  947.     Caption = 'See Priority of task'
  948.     TabOrder = 10
  949.     OnClick = SeePriorClick
  950.   end
  951.   object WorkDTaskFlags: TButton
  952.     Left = 14
  953.     Top = 284
  954.     Width = 169
  955.     Height = 25
  956.     Caption = 'Get Work Dir & Get Task Flags'
  957.     TabOrder = 11
  958.     OnClick = WorkDTaskFlagsClick
  959.   end
  960.   object Button12: TButton
  961.     Left = 14
  962.     Top = 313
  963.     Width = 169
  964.     Height = 25
  965.     Caption = 'New scheduled task'
  966.     Font.Charset = DEFAULT_CHARSET
  967.     Font.Color = 16744448
  968.     Font.Height = -11
  969.     Font.Name = 'MS Shell Dlg 2'
  970.     Font.Style = [fsBold]
  971.     ParentFont = False
  972.     TabOrder = 12
  973.     OnClick = Button12Click
  974.   end
  975.   object ApplicTask: TButton
  976.     Left = 14
  977.     Top = 373
  978.     Width = 169
  979.     Height = 25
  980.     Caption = 'Set Application Name'
  981.     TabOrder = 13
  982.     OnClick = ApplicTaskClick
  983.   end
  984.   object Planification: TButton
  985.     Left = 14
  986.     Top = 343
  987.     Width = 169
  988.     Height = 25
  989.     Caption = 'Set Trigger = Creer planification'
  990.     TabOrder = 14
  991.     OnClick = PlanificationClick
  992.   end
  993.   object SetTaskAccount: TButton
  994.     Left = 14
  995.     Top = 401
  996.     Width = 169
  997.     Height = 25
  998.     Caption = 'Account'
  999.     TabOrder = 15
  1000.     OnClick = SetTaskAccountClick
  1001.   end
  1002.   object RichEdit1: TRichEdit
  1003.     Left = 360
  1004.     Top = 344
  1005.     Width = 305
  1006.     Height = 201
  1007.     Font.Charset = DEFAULT_CHARSET
  1008.     Font.Color = 12615680
  1009.     Font.Height = -11
  1010.     Font.Name = 'MS Shell Dlg 2'
  1011.     Font.Style = []
  1012.     Lines.Strings = (
  1013.       'Short Explanations'
  1014.       ''
  1015.       'Load task and infos'
  1016.       'Will read all the existing tasks and display infos about them'
  1017.       ''
  1018.       'New Scheduled task'
  1019.       'Create a new task called 001000 if it doesn'#39't exist. '
  1020.       'After thisstep, you need to select the task called Set '
  1021.       'trigger (to add date, time...) to this task. '
  1022.       'And finally, you need to click on the Account button to '
  1023.       'supply the password and username.'
  1024.       'That'#39's all.'
  1025.       ''
  1026.       'Note all is hardcoded in this demo (name of the task, date '
  1027.       'and '
  1028.       'time of execution ...). In a real application, it will be '
  1029.       'necessary to dynamiccaly supply those infos.'
  1030.       ''
  1031.       'Hope this help.'
  1032.       '')
  1033.     ParentFont = False
  1034.     ScrollBars = ssVertical
  1035.     TabOrder = 16
  1036.   end
  1037.   object ImageList1: TImageList
  1038.     Left = 584
  1039.     Top = 264
  1040.   end
  1041. end
Advertisement
RAW Paste Data Copied
Advertisement