Solved

Task Scheduler

Posted on 2006-11-16
15
6,553 Views
Last Modified: 2011-04-14
Hi there,
I want to build a delphi application that manages tasks in Windows Schedular.
list, add, delete, change : task,time ...etc
please help by example.

regards,
Alim
0
Comment
Question by:alim_maze
  • 8
  • 4
  • 3
15 Comments
 
LVL 28

Expert Comment

by:ciuly
ID: 17958530
0
 

Author Comment

by:alim_maze
ID: 17958932
Oh' !
I allready went through these steps !
it could be easier if we could use in Delphi the netapi32.lib:
NetScheduleJobAdd  
NetScheduleJobDel
NetScheduleJobEnum
NetScheduleJobGetInfo

I got it from from API help : Schedule Functions


I still need answers/help ..

0
 
LVL 28

Expert Comment

by:ciuly
ID: 17959194
you can. that is what I have said as the 3rd option: implement from bottom up. that means importing all function, writing all structures, etc etc,

ex:

function NetScheduleJobAdd(Servername: LPCWSTR; Buffer: Pointer;
  var JobId: DWORD): dword; stdcall; external 'netapi32.dll' name 'NetScheduleJobAdd';

I've done a search for you to see if anyone did this before and made it public: found this: http://www.koders.com/delphi/fidADD9D8BAFB7F5894A45785381B15903F84B004F7.aspx

so just install jvcl and include in teh uses clause: lm.
0
 
LVL 9

Expert Comment

by:bernani
ID: 17960871
Hi,

Maybe you could download the file TaskScheduler.zip on http://delphi-jedi.org.

The zip contains a really complete TaskScheduler demoand show how to manage, create, delete, start tasks ..... and a lot more.

Header of the unit unit MsTask;

{******************************************************************}
{                                                                  }
{       Borland Delphi Runtime Library                             }
{       MS Task Scheduler interface unit                           }
{                                                                  }
{ Portions created by Microsoft are                                }
{ Copyright (C) 1995-1999 Microsoft Corporation.                   }
{ All Rights Reserved.                                             }
{                                                                  }
{ The original file is: mstask.h, released 12 May 1999.            }
{ The original Pascal code is: MsTask.pas, released 17 July 2000.  }
{ The initial developer of the Pascal code is Markus Pingel        }
{ (mpingel@vob.de).                                                }
{                                                                  }
{ Portions created by Markus Pingel are                            }
{ Copyright (C) 1999 Markus Pingel.                                }
{                                                                  }
{ Portions created by Marcel van Brakel are                        }
{ Copyright (C) 1999 Marcel van Brakel.                            }
{                                                                  }
{ Contributor(s): Sunish Issac  (sunish@nettaxi.com)               }
{                                                                  }
{ Obtained through:                                                }
{ Joint Endeavour of Delphi Innovators (Project JEDI)              }
{                                                                  }
{ You may retrieve the latest version of this file at the Project  }
{ JEDI home page, located at http://delphi-jedi.org                }
{                                                                  }
{ The contents of this file are used with permission, subject to   }
{ the Mozilla Public License Version 1.1 (the "License"); you may  }
{ not use this file except in compliance with the License. You may }
{ obtain a copy of the License at                                  }
{ http://www.mozilla.org/MPL/                                      }
{                                                                  }
{ Software distributed under the License is distributed on an      }
{ "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or   }
{ implied. See the License for the specific language governing     }
{ rights and limitations under the License.                        }
{                                                                  }
{******************************************************************}

unit MsTask;

____________________________

Hope this can help.

0
 

Author Comment

by:alim_maze
ID: 17967343
I got the TaskScheduler.zip
I encountered some bugs (constant object cannot be passed as var parameter) .. etc
I barely could run the demo , then many runtime errors raised up !

Is it that difficult to add/list jobs to schedular ??!!

I still need a valid solution , this was close (I guess!)

Regards,
Alim
0
 
LVL 9

Expert Comment

by:bernani
ID: 17969908
Hi,

I've compiled the demo from Jedi and I got no error. It's the same for the demo downloaded from codecentral (http://codecentral.borland.com/Item.aspx?id=16007 )

You say:
I encountered some bugs (constant object cannot be passed as var parameter) .. etc : mho the error you mention is an error in your code , not in the demo.

If you read the code of the demo, you have all the elements to reach your goal. You'll need to practice a little before you can find your own way to do it. It's not necessarily easy and short. See all the needed code only to display the page property of the task scheduler.  

And look at this (to display the task property sheet)
http://www.experts-exchange.com/Programming/Programming_Languages/Delphi/Q_21522485.html?query=task+scheduler&topics=85

procedure DisplayTaskPropertySheet(JobName: String);

http://www.experts-exchange.com/Programming/Programming_Languages/Delphi/Q_21477874.html?query=task+scheduler&topics=85}

// Open the Scheduler Tasks Window

ShellExecute(
Handle,  
nil,
'::{20D04FE0-3AEA-1069-A2D8-08002B30309D}\::{21EC2020-3AEA-1069-A2DD-08002B30309D}\
::{D6277990-4C6A-11CF-8D87-00AA0060F5BF}',
'',
'',
SW_SHOWNORMAL
);


There is also a good demo in the Jcl (Jedi Code Libray - downloadable at http://sourceforge.net/projects/jcl/).
In the Folder example\windows\task you'll find a working demo containing also a way to add, delete ... tasks:

    procedure actTaskPropUpdate(Sender: TObject);
    procedure actTaskPropExecute(Sender: TObject);
    procedure actTaskAddExecute(Sender: TObject); /// add a task
    procedure actTaskDeleteExecute(Sender: TObject); // delete a task
    procedure DataModuleCreate(Sender: TObject);
    procedure DataModuleDestroy(Sender: TObject);
    procedure actTaskRefreshExecute(Sender: TObject);
    procedure actTaskRunExecute(Sender: TObject);
    procedure actTaskStopExecute(Sender: TObject);
    procedure actTaskStopUpdate(Sender: TObject);
    procedure actTaskRunUpdate(Sender: TObject);
    procedure actFileExitExecute(Sender: TObject);


Good luck.
0
 
LVL 9

Expert Comment

by:bernani
ID: 17969932

I forgot to say:

The demo uses the jclTask.pas Unit and you'll see if you download the package that to add or delete a task you only to have code like this:

procedure TDM.actTaskAddExecute(Sender: TObject);
var
  TaskName: string;
  ATask: TJclScheduledTask;
begin
  TaskName := 'unnnamed';
  if InputQuery('Please input a task name', 'Task Name', TaskName) then
  try
    ATask := Task.Add(TaskName);
    if ATask.ShowPage then
    begin
      ATask.Save;
      ATask.Refresh;
      if Assigned(FOnRefresh) then FOnRefresh(Self);
    end
    else
    begin
      Task.Remove(ATask);
    end;
  except
    on E: Exception do
      {$IFDEF COMPILER6_UP}
      ApplicationShowException(E);
      {$ELSE}
      Application.ShowException(E);
      {$ENDIF}
  end;
end;

procedure TDM.actTaskDeleteExecute(Sender: TObject);
begin
  Task.Remove(SelectedTask);
  if Assigned(FOnRefresh) then FOnRefresh(Self);
end;

and so on ....

_______________________________________________
Hope this can help.
0
Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

 

Author Comment

by:alim_maze
ID: 17971483
I appreciate your hardwork bernani  ..
I've installed JEDI (\jcl1.97-build2172\jcl\Install.bat)

when compiling
C:\Projects\Schedular\jcl1.97-build2172\jcl\examples\windows\tasks\TaskDemo.dpr
it gives :
[Fatal Error] TaskDemoDataModule.pas(9): Unit JclTask was compiled with a different version of MSTask.ITaskScheduler


?!
what could be the reason?!
I use D7

Regards,
Alim
0
 
LVL 9

Expert Comment

by:bernani
ID: 17971554

Hi,

I believe (I'm not sure) that when you receive this kind of warning error, it often means that there is somewhere an old reference to a declaration or unit.

As you have previously used the unit MsTask.pas from the TaskScheduler demo, it can occur that somewhere in your IDE search path or library path you reference the MsTask.pas unit. You don't need the content of this unit for the jcl. It has his own unit (jcTask.pas).

At first, uninstall or remove all reference in your library path to the previous used unit MsTask.pas used by the TaskScheduler demo.

Try to recompile the jcl and run the demo again to see if it works..

Check also your project to see if it doesn't reference somewhere the MTask.pas unit and check the use clause of your project also.

Eventually, you can uninstall the jcl and the re-install. With the jcl installation procedure, it's an easy step. But don't forget to check you have not the least reference to MsTask somewhere ...

Note that you do't really need the TaskDemoDataModule: it's an easy way to manage and centralize the menu items and their event's code. You could past the content of each procedure in the correspondent mainmenu.itemclick.

__________________________________

Hope this can be  useful.
0
 
LVL 28

Expert Comment

by:ciuly
ID: 17971594
I suggest just deleting all JclTask.dcu and MSTask.dcu from everywhere. they will be recompiled correctly.
0
 
LVL 9

Expert Comment

by:bernani
ID: 17971716

Hi,

I believe that deleting only the dcu isn't enough.

It'd be better to use the uninstall/install procedure provided with the jcl.

In this way, all reference, files, compos,... are properly removed and the reinstall occurs without problem (in general).  Moreover, the building of the demos provided with the jcl can occur at the same time of the compiling of all packages: all errors are logged during install.  

0
 

Author Comment

by:alim_maze
ID: 17971772
it seems it is not easy!
I tried the demo in another PC : it worked !
but , when trying to add new task, it calls Windows Schedular,
I am still studying the ability of just making the system do the schedule without calling Schedular GUI ..

BR,
Alim
0
 
LVL 9

Expert Comment

by:bernani
ID: 17971968
Hi alim_maze,

If you don't want use or display the Win Sched., I don't see how you can achieve your task without using a unit like MsTask.

Maybe writing your own units and implementing all by yourself. But why when the TaskScheduler demo provide all the stuff required to do it even if you need. Read the code source of the demo to see how each procedure is implemented for the task your need to perform.

As you can see, without calling the Win. Sched. GUI, it's not the easiest way but not undoable. If I have time, I try to write you a sample demo in the next days.

Maybe you can post your code in order we can check/complete and help you usefully.

Good luck.
0
 
LVL 9

Accepted Solution

by:
bernani earned 500 total points
ID: 18016022
Hi,

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.

__________________ paste code below and save as Unit1.pas __________________________
Unit 1

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Classes, Graphics,
  Controls, Forms, Dialogs,
  ActiveX, ImgList, MsTask, MsTaskUtils, Menus,
  Shellapi, StdCtrls, ExtCtrls, ComCtrls;

type
  TForm1 = class(TForm)
    Label1: TLabel;
    ListandCountTasks: TButton;
    Memo1: TMemo;
    SchedAgentEnum: TButton;
    GetTargetPC: TButton;
    ListBox1: TListBox;
    LoadTasks: TButton;
    ImageList1: TImageList;
    Image1: TImage;
    FileNameOfSelTask: TButton;
    RunSelectTask: TButton;
    TaskStatut: TButton;
    SeeParam: TButton;
    SeePrior: TButton;
    WorkDTaskFlags: TButton;
    Button12: TButton;
    ApplicTask: TButton;
    Planification: TButton;
    SetTaskAccount: TButton;
    Label2: TLabel;
    RichEdit1: TRichEdit;
    procedure FormCreate(Sender: TObject);
    procedure ListandCountTasksClick(Sender: TObject);
    procedure SchedAgentEnumClick(Sender: TObject);
    procedure GetTargetPCClick(Sender: TObject);
    procedure LoadTasksClick(Sender: TObject);
    procedure ListBox1Click(Sender: TObject);
    procedure RunSelectTaskClick(Sender: TObject);
    procedure TaskStatutClick(Sender: TObject);
    procedure SeeParamClick(Sender: TObject);
    procedure SeePriorClick(Sender: TObject);
    procedure WorkDTaskFlagsClick(Sender: TObject);
    procedure Button12Click(Sender: TObject);
    procedure ApplicTaskClick(Sender: TObject);
    procedure PlanificationClick(Sender: TObject);
    procedure SetTaskAccountClick(Sender: TObject);
    procedure FileNameOfSelTaskClick(Sender: TObject);
  private
    { Déclarations privées }
    Function Init(Lbl:TLabel): HRESULT;

  public
    { Déclarations publiques }
  end;

var
  Form1: TForm1;
  SchedulingAgent: ITaskScheduler;
  ScheduledWorkItem: IScheduledWorkItem;
  pIPersistFile: IPersistFile;
  Task: ITask;

  MyComputerName,
  MyAppname,
  MyParameters,
  MyWorkingDir,
  MyTaskFlags : String;

  implementation

uses AuxProcs;

{$R *.DFM}

///////////////////////////////////////////////////////////

Function TForm1.Init(Lbl:TLabel): HRESULT;
begin
  Result := S_OK;
  Lbl.Caption:= '';
  if not assigned(SchedulingAgent) then
  begin
    Result := ActiveX.CoInitialize(nil);
    if Result <> S_OK then
    begin
      ActiveX.CoUninitialize;
      Lbl.caption:= 'Error in ActiveX.CoInitialize. Error Code: ' + IntToHex(Result, 8);
      Application.Terminate;
    end else
    Lbl.Caption:= 'OK with ActiveX.CoInitialize';

    Result := ActiveX.CoCreateInstance(
       CLSID_CSchedulingAgent,
       nil,
       CLSCTX_INPROC_SERVER,
       IID_ITaskScheduler,
       SchedulingAgent);

    if Result <> S_OK then
    begin
    Lbl.caption:= 'Error in ActiveX.CoCreateInstance. Error Code: ' + IntToHex(Result, 8);
    Application.Terminate;
    end;
  end;
end;

///////////////////////////////////////////////////////////

Function GetITask(TaskName: string;Lbl:TLabel): ITask;
var
  PITask: IUnknown;
  hr: HRESULT;
begin
  Lbl.caption:= '';
  hr := SchedulingAgent.Activate(AuxProcs.StrToWide(TaskName), IID_ITask, PITask);
  if hr = S_OK then
  Result := ITask(PITask)
  else
  begin
    Lbl.Caption:= 'Error in SchedulingAgent.Activate. Error Code: ' + IntToHex(hr, 8);
    Result := nil;
  end;
end;

///////////////////////////////////////////////////////////

Function SaveTask(Lbl:TLabel): HRESULT;
begin
  Result := -1;
  Task.QueryInterface(IID_IPersistFile, pIPersistFile);
  if pIPersistFile <> nil then
  begin
    Result := pIPersistFile.Save(nil, true);
  end
  else
  Lbl.caption:= 'Error in Task.QueryInterface(IID_IPersistFile, pIPersistFile): ';
end;

///////////////////////////////////////////////////////////

Function DeleteTask(JobName: string): HRESULT;
begin
  Result := SchedulingAgent.Delete(StrToWide(JobName));
end;

///////////////////////////////////////////////////////////

Procedure IsOkScheduler(Lbl: TLabel);
var
  hr: HRESULT;
begin
  Lbl.Caption:= '';
  hr := StartScheduler;
  if hr = ERROR_SUCCESS then
  Lbl.Caption:= 'Task Scheduler has started successfully.'
  else
  Lbl.Caption := 'Task Scheduler didn''t start. Error Code:' + IntTohex(hr, 8);
end;

///////////////////////////////////////////////////////////
procedure SetTargetComputer(Txt:TMemo);
var
  hr: HResult;
  ComputerName: PWideChar;
begin
//$80070035 networkpath not found
//$80070005 General access denied
//passing nil as computername should return local machine target computer
  ComputerNAme := StrToWide(MyComputerName);
  Txt.Lines.Add('Trying to set Target Computername to:' + MyComputerName);
  hr := SchedulingAgent.SetTargetComputer(ComputerName);
  if hr = S_OK then
  Txt.Lines.Add('Target Computername is set to:' + WideCharToString(ComputerNAme))
  else
  begin
    if hr = SCHED_E_SERVICE_NOT_INSTALLED then
    Txt.Lines.Add('TargetComputer does not have service installed');
    Txt.Lines.Add('SetTargetComputer failed with error code:$' + IntTohex(hr, 8));
  end;
end;
//-----------------------------------------------------------
procedure TForm1.FormCreate(Sender: TObject);
begin
IsOkScheduler(Label1);
LoadTasksClick(self);
end;
//-----------------------------------------------------------
procedure TForm1.SchedAgentEnumClick(Sender: TObject);
var
  hr: HRESULT;
  pEnum: IEnumWorkItems;
begin
Memo1.clear;
Init(Label2);
hr := SchedulingAgent.Enum(pEnum);
   if hr <> S_OK then
   Memo1.Lines.Add('SchedulingAgent.Enum Result:' + IntTohex(hr, 8))
   else
   Memo1.Lines.Add('SchedulingAgent.Enum Result: OK');
end;
//-----------------------------------------------------------
procedure TForm1.GetTargetPCClick(Sender: TObject);
var
  ComputerName: PWideChar;
  hr: HResult;
begin
Memo1.clear;
Init(Label2);
hr := SchedulingAgent.GetTargetComputer(ComputerName);
if hr = S_OK then
  begin
  Memo1.Lines.Add('Target Computername is :' + WideCharToString(ComputerNAme) + #13#10);
  MyComputerName := WideCharToString(ComputerNAme);
  end
  else
  Memo1.Lines.Add('GetTargetComputer failed with error code :$' + IntTohex(hr, 8) + #13#10);
end;
//-----------------------------------------------------------
procedure TForm1.ListandCountTasksClick(Sender: TObject);
var
hr: HRESULT;
pEnum: IEnumWorkItems;
TaskNames: PLPWSTR;
dwFetched: DWORD;
szString: string;
Appname: PWideChar;
begin
Memo1.clear;
Listbox1.clear;
GetTargetPCClick(self);
hr := SchedulingAgent.Enum(pEnum);
while (pEnum.Next(1, TaskNames, dwFetched) = 0) and (dwFetched > 0) do
  begin
  szString := WideCharToString(TaskNames^);
  Memo1.Lines.Add('Enum.Next fetched: ' + IntToStr(dwFetched) + ' item(s).');
  Memo1.Lines.Add('Taskname: ' + szString);
  Memo1.Lines.Add('---------------------');
  ListBox1.Items.Add(szString);
  ActiveX.CoTaskMemFree(TaskNames);
  end;
end;
//-----------------------------------------------------------
procedure TForm1.FileNameOfSelTaskClick(Sender: TObject);
var
i: integer;
Appname: PWideChar;
begin
Memo1.clear;
 for i:= 0 to ListBox1.items.count -1 do
 begin
   if listbox1.Selected[i] then
      begin
      Memo1.clear;
      Task := GetITask(ListBox1.Items[ListBox1.Itemindex],label2);
      Task.GetApplicationName(Appname);
      Memo1.lines.Add('The task  : ' + ListBox1.Items[ListBox1.Itemindex]);
      Memo1.lines.Add('Call the following application file: ');
      Memo1.lines.Add(AppName);
      end;
 end;
end;
//-----------------------------------------------------------
procedure TForm1.LoadTasksClick(Sender: TObject);
var
  hr: HRESULT;
  pEnum: IEnumWorkItems;
  TaskNames: PLPWSTR;
  dwFetched: DWORD;
  szString: string;
  TriggCount: Word;
  Appname: PWideChar;
  IconIndex: Word;
  Icon: TIcon;
  TriggStr: PwideChar;
  NextRunTime: _SYSTEMTIME;
begin
Memo1.clear;
Listbox1.Clear;

Icon := TIcon.Create;
IconIndex := 0;

GetTargetPCClick(self);
Init(label2);
hr := SchedulingAgent.Enum(pEnum);

ImageList1.Clear;

while (pEnum.Next(1, TaskNames, dwFetched) = 0) and (dwFetched > 0) do
  begin

//Taskname from enum
    szString := WideCharToString(TaskNames^);
    Memo1.lines.Add(szString);
    ListBox1.Items.Add(szString);  // add the name of each existing task
//for getting the icon from filename of task
    Task := GetITask(szString,label2);
    Task.GetApplicationName(Appname);

    if MyComputerName = '\\' + GetLocalComputerName then
    begin
    Memo1.lines.Add('Name of application: '+(PChar(WideCharToString(Appname))));
    Icon.Handle := ExtractAssociatedIcon(Hinstance, PChar(WideCharToString(Appname)), IconIndex);
    Image1.Picture.Icon:= Icon;
    end;

    Task.GetWorkingDirectory(Appname);
    Memo1.lines.Add('GetWorkingDir: '+WideCharToString(Appname));

//GetStatus
    Task.GetStatus(hr);
    Memo1.lines.Add(MessageFromValue(hr));
//GetNextRecentTime
    hr := Task.GetNextRunTime(NextRunTime);
    if hr = S_OK then
    Memo1.lines.Add('NextRunTime: '+ DateTimeToStr(SystemTimeToDateTime(NextRunTime)))
    else
    Memo1.lines.Add('Next RunTime'+ MessageFromValue(hr)); ;
//GetMostRecentTime
    hr := Task.GetMostRecentRunTime(NextRunTime);
    if hr = S_OK then
    Memo1.lines.Add('Recent runtime: ' + DateTimeToStr(SystemTimeToDateTime(NextRunTime)))
    else
    Memo1.lines.Add('Recent runtime: ' +  MessageFromValue(hr)); ;
//GetTriggerString and GetTriggerCount
    hr := Task.GetTriggerCount(TriggCount);
    if hr = S_OK then
      if TriggCount > 1 then
      begin
        Memo1.lines.Add('Multiple schedule times');
      end
      else
      begin
        Task.GetTriggerString(0, TriggStr);
        if TriggStr <> nil then
        Memo1.lines.Add('Planification: ' + WideCharToString(TriggStr));

      end;
              Memo1.lines.Add('');
      ActiveX.CoTaskMemFree(TaskNames);
  end;
Icon.free;
end;
//-----------------------------------------------------------
procedure TForm1.TaskStatutClick(Sender: TObject);
var
  hr: HRESULT;
  i: integer;
begin
Memo1.clear;
 for i:= 0 to ListBox1.items.count -1 do
 begin
   if listbox1.Selected[i] then
      begin
      Task := GetITask(Listbox1.Items[i],label2);
      Task.GetStatus(hr);
      Memo1.Lines.Add('GetStatus returned value :' + IntToHex(hr, 8));
      Memo1.Lines.Add('Message from value : ' +  MessageFromValue(hr));
      end;
  end;
end;
//-----------------------------------------------------------
procedure TForm1.SeeParamClick(Sender: TObject);
var
i: integer;
pParameters: PWideChar;
begin
Memo1.clear;
for i:= 0 to ListBox1.items.count -1 do
begin
   if listbox1.Selected[i] then
      begin
      Task := GetITask(Listbox1.Items[i],label2);
      Task.GetParameters(pParameters);
         if WideCharToString(pParameters) = '' then
         Memo1.Lines.Add('GetParameters did not return any value as there are no parameters' + #13#10)
         else
         Memo1.Lines.Add('GetParameters returned :' + WideCharToString(pParameters) + #13#10);
         MyParameters := WideCharToString(pParameters);
      end;
  end;
end;
//-----------------------------------------------------------
procedure TForm1.SeePriorClick(Sender: TObject);
var
i: integer;
Priority: Cardinal;
PriorityStr: string;
begin
Memo1.clear;
for i:= 0 to ListBox1.items.count -1 do
begin
 if listbox1.Selected[i] then
      begin
      Task := GetITask(Listbox1.Items[i],label2);
      Task.GetPriority(Priority);
      case Priority of
           REALTIME_PRIORITY_CLASS: PriorityStr := 'Realtime';
           HIGH_PRIORITY_CLASS: PriorityStr := 'High';
           NORMAL_PRIORITY_CLASS: PriorityStr := 'Normal';
           IDLE_PRIORITY_CLASS: PriorityStr := 'Idle';
      end;
      Memo1.Lines.Add('The priority of the task is ' + PriorityStr + #13#10);
      end;
 end;
end;
//-----------------------------------------------------------
procedure TForm1.WorkDTaskFlagsClick(Sender: TObject);
var
//Appname: PWideChar;
i: integer;
pWorkingDir: PWideChar;
PdwFlags: Cardinal;
begin

for i:= 0 to ListBox1.items.count -1 do
begin
   if listbox1.Selected[i] then
      begin
      Memo1.clear;
      Task.GetWorkingDirectory(pWorkingDir);
      if WideCharToString(pWorkingDir) = '' then
         Memo1.Lines.Add('GetWorkingDirectory did not return any value as there are no parameters')
         else
         Memo1.Lines.Add('GetWorkingDirectory returned: ' + WideCharToString(pWorkingDir));
         MyWorkingDir := WideCharToString(pWorkingDir);

         Task.GetTaskFlags(PdwFlags);
         Memo1.Lines.Add('GetTask Flags returned value of PdwFlags ' + IntToStr(PdwFlags));
         MyTaskFlags := IntToStr(PdwFlags);
         end;
     end;
end;
//-----------------------------------------------------------
procedure TForm1.ListBox1Click(Sender: TObject);
//var
//  Appname: PWideChar;
//  szString: string;
//  IconIndex: Word;
//  Icon: TIcon;
//  i: integer;
begin
//Memo1.clear;
// for i:= 0 to ListBox1.items.count -1 do
// begin
//
//   if listbox1.Selected[i] then
//      begin
//      Memo1.clear;
//      Task := GetITask(ListBox1.Items[ListBox1.Itemindex],label2);
//      Task.GetApplicationName(Appname);
//      Memo1.Lines.Add('Application Name is: ' + WideCharToString(Appname));
//      MyAppname:= WideCharToString(Appname);
//
//      Icon := TIcon.Create;
//      IconIndex := 0;
//
//    if MyComputerName = '\\' + GetLocalComputerName then
//    begin
//    Memo1.lines.Add('Name of application: '+(PChar(WideCharToString(Appname))));
//    Icon.Handle := ExtractAssociatedIcon(Hinstance, PChar(WideCharToString(Appname)), IconIndex);
//    Image1.Picture.Icon:= Icon;
//    end;
//    Icon.free;
//    end;
//end;
end;
//-----------------------------------------------------------
procedure TForm1.ApplicTaskClick(Sender: TObject);
var
Priority: Cardinal;
PriorityStr: string;
hr: HRESULT;
Idx : integer;
begin
Memo1.clear;
Idx:= ListBox1.Itemindex;

Task := GetITask(Listbox1.Items[idx],label2);
MyAppName:= 'Calc.exe';
HR := Task.SetApplicationName(StrToWide(MyAppname));

if HR = S_OK then
Memo1.Lines.Add('Application Name is set to :' + MyAppname)
else
begin
Memo1.Lines.Add('Error in setting Application Name to :' + MyAppname + 'Error Code:' + IntTohex(HR, 8));
Exit;
end;

SaveTAsk(Label2);
end;
//-----------------------------------------------------------
procedure TForm1.SetTaskAccountClick(Sender: TObject);
var
i: integer;
Username, Password: string;
hr: HRESULT;
uname, pass: PWideChar;
PdwFlags: Cardinal;

begin
Memo1.clear;

 if ListBox1.items.count -1 > 0 then
 begin
   for i:= 0 to Listbox1.Items.count - 1 do
   if listbox1.Selected[i] then
      begin

      Username := 'Bernard';
      Password := '';
      GetMem(uname, 255);
      GetMem(pass, 255);
      StringToWideChar(Username, uname, Length(UserName) + 1);
      StringToWideChar(Password, pass, Length(Password) + 1);

  Task := GetITask(Listbox1.Items[i],label2);
  Task.SetFlags(8192);
  hr := Task.SetAccountInformation(uname, pass);
  SaveTask(Label2);
LoadTasksClick(Self);
  case hr of
    S_OK:
    begin
    Memo1.Lines.Add('SetAccountInformation success');
    end;
    E_ACCESSDENIED: Memo1.Lines.Add('The caller does not have permission to perform the operation. For more information, see Remarks.');
    E_INVALIDARG: Memo1.Lines.Add('The arguments are not valid.');
    E_OUTOFMEMORY: Memo1.Lines.Add('Not enough memory is available.');
    else
    begin
    Memo1.Lines.Add(MessageFromValue(hr));
    Memo1.Lines.Add('SetAccountInformation failed with errorcode :' + IntTohex(hr, 8) + #13#10);
    end;
  end;
  FreeMem(uname);
  FreeMem(pass);
  HR := Task.SetTaskFlags(StrToInt('$2000'));

  if HR = S_OK then Memo1.Lines.Add('SetTaskFlags set to :' + myTaskFlags)
  else
  begin
  Memo1.Lines.Add('Error in setting flags to :' + MyTaskFlags + 'Error Code:' + IntTohex(HR, 8));
  exit;
  end;

  if hr <> S_OK then
  Memo1.lines.add('Save task failed with error code' + IntTohex(hr, 8) + #13#10);
      end;
Task.Run;
// Uncomment line under to see the windows dialog sched.
//Task.EditWorkItem(self.handle,0);
 end;
end;
//-----------------------------------------------------------
procedure TForm1.RunSelectTaskClick(Sender: TObject);
var
  hr: HRESULT;
  i: integer;
begin
 for i:= 0 to ListBox1.items.count -1 do
 begin

   if listbox1.Selected[i] then
      begin
      Task := GetITask(Listbox1.Items[i],label2);
      HR := Task.SetTaskFlags(StrToInt('$2000'));//MyTaskFlags));
      hr := Task.Run;
      Memo1.Lines.Add('Run Application Error Code :' + IntTohex(hr, 8) + #13#10);
      Memo1.Lines.Add(MyAppName);//Listbox1.Items[i]);
      //  BtnGetTasksClick(self); //for updating
      end;
  end;
end;
//-----------------------------------------------------------
procedure TForm1.Button12Click(Sender: TObject);
var
  Appname: PWideChar;
  szString: string;
  IconIndex: Word;
  Icon: TIcon;
  i: integer;
  pWorkingDir: PWideChar;
  PdwFlags: Cardinal;
//
  HR : HRESULT;
  TaskName: string;
  WorkItem: IUnknown;
    Creator: PWideChar;
    MaxRunTime: DWORD;
begin
Memo1.clear;
TaskName := '001000'; // name of the task - here hardcoded
Init(Label2);

HR := SchedulingAgent.NewWorkItem(
           StrToWide(TaskName),
           CLSID_CTask,
           IID_IScheduledWorkItem,
           WorkItem);

Task := ITask(WorkItem); //required for save
ScheduledWorkItem := IScheduledWorkItem(WorkItem);

if HR = S_OK then
begin
Listbox1.items.add(Taskname);
Memo1.Lines.Add(Taskname + ' created successfully');
Listbox1.Update;
end
else
begin
Memo1.Lines.Add('Could not create the job ' + taskname + '. Error Code: ' + IntTohex(hr, 8));
exit;
end;

hr := SaveTAsk(Label2);

if hr <> S_OK then Memo1.lines.add('Save task failed with error code: ' + IntTohex(hr, 8));


Memo1.clear;

Task := GetITask(Taskname,label2);
Task.GetApplicationName(Appname);
Memo1.Lines.Add('Application Name is: ' + WideCharToString(Appname));
MyAppname:= WideCharToString(Appname);

   Icon := TIcon.Create;
   IconIndex := 0;

    if MyComputerName = '\\' + GetLocalComputerName then
    begin
    Memo1.lines.Add('Name of application: '+(PChar(WideCharToString(Appname))));
    Icon.Handle := ExtractAssociatedIcon(Hinstance, PChar(WideCharToString(Appname)), IconIndex);
    Image1.Picture.Icon:= Icon;

    Task := GetITask(TaskName,label2);
    Task.GetCreator(Creator);
    Memo1.Lines.Add('The Name of the Creator of the selected job is : ' + WideCharToString(Creator));

    Task := GetITask(Taskname,label2);
    Task.GetMaxRunTime(MaxRunTime);
    Memo1.Lines.Add('GetMaxRunTime returned: ' + IntToStr(MaxRunTime) + ' milliseconds');
    end;

    Icon.free;
//    end;

end;
//-----------------------------------------------------------
procedure TForm1.PlanificationClick(Sender: TObject);
var
i: integer;
  hr: HRESULT;
  piNewTrigger: Word;
  ITTrigger: ITaskTrigger;
  TaskTrig: TTaskTRIGGER;
  Count: Word;
begin
memo1.clear;
 for i:= 0 to ListBox1.items.count -1 do
 begin
   if listbox1.Selected[i] then
      begin
      Task := GetITask(Listbox1.Items[i],label2);
      HR := Task.CreateTrigger(piNewTrigger, ITTrigger);

      if HR = S_OK then
      Memo1.Lines.Add('Create Trigger success ')
      else
      begin
      Memo1.Lines.Add('Error in Create Trigger Error Code:' + IntToHex(HR, 8));
      exit;
      end;

      ZeroMemory(@TaskTrig, sizeof(TASK_TRIGGER));
      TaskTrig.cbTriggerSize := sizeof(TASK_TRIGGER);
      TaskTrig.Reserved1 := 0;
      TaskTrig.wBeginYear := 2006;
      TaskTrig.wBeginMonth := 11;
      TaskTrig.wBeginDay := 27;
      TaskTrig.wEndYear := 2006;
      TaskTrig.wEndMonth := 11;
      TaskTrig.wEndDay := 30;
      TaskTrig.wStartHour := 16;
      TaskTrig.wStartMinute := 25;
      TaskTrig.MinutesDuration := 0;
      TaskTrig.MinutesInterval := 0;
      TaskTrig.rgFlags := 0;
{rgFlags
Value that describes the task trigger's behavior.
This value is a combination of the following flags:
TASK_TRIGGER_FLAG_HAS_END_DATE
Trigger structure's end date is valid.
If this flag is not set, the end date data is ignored and
the trigger will be valid indefinitely.

TASK_TRIGGER_FLAG_KILL_AT_DURATION_END
Task will be terminated at the end of the active trigger's
lifetime. At the duration end, the scheduling agent
first sends a WM_CLOSE message to
the associated application. If the application hasn't
exited in three minutes,TerminateProcess runs.
If more than one instance of a task is running,
all instances are terminated.

TASK_TRIGGER_FLAG_DISABLED
Task trigger is inactive.
}

  TaskTrig.TriggerType := TASK_TIME_TRIGGER_ONCE;
  TaskTrig.wRandomMinutesInterval := 0;
  TaskTrig.Reserved2 := 0;

  hr := ITTrigger.SetTrigger(@TaskTrig);
  if (hr <> S_OK) then
  begin
    Memo1.Lines.Add(MessageFromValue(hr));
    exit;
  end;
    SaveTAsk(Label2);
  end;

  end; {for}

//display properties of trigger
  try Task.GetTriggerCount(Count)except {} end;
  if Count <= 0 then
  begin
    ShowMessage('No triggers');
    Exit;
  end;

  Task.GetTrigger(0, ITTrigger);
  TaskTrig.cbTriggerSize := sizeof(TASK_TRIGGER);

  hr := ITTrigger.GetTrigger(@TaskTrig);
  if (hr <> S_OK) then
  begin
  Memo1.clear;
  Memo1.Lines.Add(MessageFromValue(hr));
  exit;
  end;
  Memo1.Lines.Add('Get Trigger Returned :');
  Memo1.Lines.Add(' Begin Year:' + IntToStr(TaskTrig.wBeginYear) + #13#10 +
    ' Begin Month:' + IntToStr(TaskTrig.wBeginMonth) + #13#10 +
    ' Begin Day:' + IntToStr(TaskTrig.wBeginDay) + #13#10 +
    ' End Year:' + IntToStr(TaskTrig.wEndYear) + #13#10 +
    ' End Month:' + IntToStr(TaskTrig.wEndMonth) + #13#10 +
    ' End Day:' + IntToStr(TaskTrig.wEndDay));
end; {proc}

end.

__________________ paste code below and save as Projec1.dpr __________________________
program Project1;

uses
  Forms,
  Unit1 in 'Unit1.pas' {Form1},
  AuxProcs in 'AuxProcs.pas',
  MsTaskUtils in 'MsTaskUtils.pas';

{$R *.RES}

begin
  Application.Initialize;
  Application.CreateForm(TForm1, Form1);
  Application.Run;
end.

__________________ paste code below and save as Unit1.dfm __________________________
object Form1: TForm1
  Left = 243
  Top = 105
  Width = 696
  Height = 601
  Caption = 'Creating a scheduled task under Delphi ...'
  Color = clWhite
  Font.Charset = DEFAULT_CHARSET
  Font.Color = clWindowText
  Font.Height = -11
  Font.Name = 'MS Shell Dlg 2'
  Font.Style = []
  OldCreateOrder = False
  ShowHint = True
  OnCreate = FormCreate
  PixelsPerInch = 96
  TextHeight = 13
  object Label1: TLabel
    Left = 19
    Top = 16
    Width = 331
    Height = 13
    AutoSize = False
    Color = clBlue
    Font.Charset = DEFAULT_CHARSET
    Font.Color = clWhite
    Font.Height = -11
    Font.Name = 'MS Shell Dlg 2'
    Font.Style = [fsBold]
    ParentColor = False
    ParentFont = False
  end
  object Image1: TImage
    Left = 72
    Top = 483
    Width = 57
    Height = 46
    Center = True
  end
  object Label2: TLabel
    Left = 359
    Top = 16
    Width = 304
    Height = 13
    AutoSize = False
    Color = clYellow
    Font.Charset = DEFAULT_CHARSET
    Font.Color = clRed
    Font.Height = -11
    Font.Name = 'MS Shell Dlg 2'
    Font.Style = [fsBold]
    ParentColor = False
    ParentFont = False
  end
  object ListandCountTasks: TButton
    Left = 14
    Top = 105
    Width = 169
    Height = 25
    Caption = 'ListandCountTasks'
    TabOrder = 0
    OnClick = ListandCountTasksClick
  end
  object Memo1: TMemo
    Left = 360
    Top = 48
    Width = 303
    Height = 281
    ScrollBars = ssVertical
    TabOrder = 1
  end
  object SchedAgentEnum: TButton
    Left = 14
    Top = 45
    Width = 169
    Height = 25
    Caption = 'SchedulingAgent.Enum'
    TabOrder = 2
    OnClick = SchedAgentEnumClick
  end
  object GetTargetPC: TButton
    Left = 14
    Top = 75
    Width = 169
    Height = 25
    Caption = 'GetTargetComputer'
    TabOrder = 3
    OnClick = GetTargetPCClick
  end
  object ListBox1: TListBox
    Left = 192
    Top = 48
    Width = 161
    Height = 497
    Color = 16731983
    Columns = 1
    Font.Charset = DEFAULT_CHARSET
    Font.Color = clWhite
    Font.Height = -11
    Font.Name = 'MS Shell Dlg 2'
    Font.Style = [fsBold]
    ItemHeight = 13
    ParentFont = False
    TabOrder = 4
    OnClick = ListBox1Click
  end
  object LoadTasks: TButton
    Left = 14
    Top = 134
    Width = 169
    Height = 25
    Caption = 'Load task and infos'
    Font.Charset = DEFAULT_CHARSET
    Font.Color = clRed
    Font.Height = -11
    Font.Name = 'MS Shell Dlg 2'
    Font.Style = [fsBold]
    ParentFont = False
    TabOrder = 5
    OnClick = LoadTasksClick
  end
  object FileNameOfSelTask: TButton
    Left = 14
    Top = 164
    Width = 169
    Height = 25
    Hint = 'Select job and click '
    Caption = 'Applic. name of selected task'
    TabOrder = 6
    OnClick = FileNameOfSelTaskClick
  end
  object RunSelectTask: TButton
    Left = 14
    Top = 432
    Width = 169
    Height = 25
    Caption = 'Run application'
    TabOrder = 7
    OnClick = RunSelectTaskClick
  end
  object TaskStatut: TButton
    Left = 14
    Top = 194
    Width = 169
    Height = 25
    Caption = 'Statut of theTask'
    TabOrder = 8
    OnClick = TaskStatutClick
  end
  object SeeParam: TButton
    Left = 14
    Top = 224
    Width = 169
    Height = 25
    Caption = 'See Parameters'
    TabOrder = 9
    OnClick = SeeParamClick
  end
  object SeePrior: TButton
    Left = 14
    Top = 254
    Width = 169
    Height = 25
    Caption = 'See Priority of task'
    TabOrder = 10
    OnClick = SeePriorClick
  end
  object WorkDTaskFlags: TButton
    Left = 14
    Top = 284
    Width = 169
    Height = 25
    Caption = 'Get Work Dir & Get Task Flags'
    TabOrder = 11
    OnClick = WorkDTaskFlagsClick
  end
  object Button12: TButton
    Left = 14
    Top = 313
    Width = 169
    Height = 25
    Caption = 'New scheduled task'
    Font.Charset = DEFAULT_CHARSET
    Font.Color = 16744448
    Font.Height = -11
    Font.Name = 'MS Shell Dlg 2'
    Font.Style = [fsBold]
    ParentFont = False
    TabOrder = 12
    OnClick = Button12Click
  end
  object ApplicTask: TButton
    Left = 14
    Top = 373
    Width = 169
    Height = 25
    Caption = 'Set Application Name'
    TabOrder = 13
    OnClick = ApplicTaskClick
  end
  object Planification: TButton
    Left = 14
    Top = 343
    Width = 169
    Height = 25
    Caption = 'Set Trigger = Creer planification'
    TabOrder = 14
    OnClick = PlanificationClick
  end
  object SetTaskAccount: TButton
    Left = 14
    Top = 401
    Width = 169
    Height = 25
    Caption = 'Account'
    TabOrder = 15
    OnClick = SetTaskAccountClick
  end
  object RichEdit1: TRichEdit
    Left = 360
    Top = 344
    Width = 305
    Height = 201
    Font.Charset = DEFAULT_CHARSET
    Font.Color = 12615680
    Font.Height = -11
    Font.Name = 'MS Shell Dlg 2'
    Font.Style = []
    Lines.Strings = (
      'Short Explanations'
      ''
      'Load task and infos'
      'Will read all the existing tasks and display infos about them'
      ''
      'New Scheduled task'
      'Create a new task called 001000 if it doesn'#39't exist. '
      'After thisstep, you need to select the task called Set '
      'trigger (to add date, time...) to this task. '
      'And finally, you need to click on the Account button to '
      'supply the password and username.'
      'That'#39's all.'
      ''
      'Note all is hardcoded in this demo (name of the task, date '
      'and '
      'time of execution ...). In a real application, it will be '
      'necessary to dynamiccaly supply those infos.'
      ''
      'Hope this help.'
      '')
    ParentFont = False
    ScrollBars = ssVertical
    TabOrder = 16
  end
  object ImageList1: TImageList
    Left = 584
    Top = 264
  end
end



0
 
LVL 9

Expert Comment

by:bernani
ID: 18075302
Hi,

Maybe you can also see this project on sourceforge:

http://sourceforge.net/project/showfiles.php?group_id=109315

0

Featured Post

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

This article explains how to create forms/units independent of other forms/units object names in a delphi project. Have you ever created a form for user input in a Delphi project and then had the need to have that same form in a other Delphi proj…
In this tutorial I will show you how to use the Windows Speech API in Delphi. I will only cover basic functions such as text to speech and controlling the speed of the speech. SAPI Installation First you need to install the SAPI type library, th…
This demo shows you how to set up the containerized NetScaler CPX with NetScaler Management and Analytics System in a non-routable Mesos/Marathon environment for use with Micro-Services applications.
This video explains how to create simple products associated to Magento configurable product and offers fast way of their generation with Store Manager for Magento tool.

743 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now