Delphi使用ShellExec运行dos命令时获取返回值

时间:2011-07-20 08:28:17

标签: delphi shellexecute

如果我在命令/ dos窗口中执行以下命令

schtasks.exe /delete /tn "MMP4CDownloadCheck" /f

结果如下

ERROR: The specified task name "MMP4CDownloadCheck" does not exist in the system.

使用ShellExec从我的应用程序(Delphi XE)中运行相同命令时是否可以检索返回值?

我按如下方式运行:

AHWnd := ShellExecute(0, nil, PChar('schtasks.exe'), PChar(Params), nil, SW_HIDE);

提前谢谢你。

问候,彼得。

1 个答案:

答案 0 :(得分:5)

不在ShellExecute。可能使用ShellExecuteExCreateProcess。您需要调用GetExitCodeProcess,为此您需要创建过程的句柄。

对于您的具体情况,最好避免拨打schtasks.exe并使用Task Scheduler API。请参阅JCL中的JclTask

我在我的一个旧单元中找到的示例用法(对于Delphi 2007):

procedure TSetupDataModule.AddDatabaseBackupTask;
var
  FileName: WideString;
  Scheduler: ITaskScheduler;
  Task: ITask;
  TaskPersist: IPersistFile;
  TriggerIndex: Word;
  Trigger: ITaskTrigger;
  TriggerData: TTaskTrigger;
begin
  OleCheck(CoCreateInstance(CLSID_CTaskScheduler, nil, CLSCTX_INPROC_SERVER, IID_ITaskScheduler, Scheduler));
  OleCheck(Scheduler.NewWorkItem(BackupTaskName, CLSID_CTask, IID_ITask, IUnknown(Task)));

  FileName := WideIncludeTrailingPathDelimiter(FDatabaseTargetDir) + BackupToolFileName;
  OleCheck(Task.SetApplicationName(PWideChar(FileName)));

  OleCheck(Task.SetWorkingDirectory(PWideChar(WideExcludeTrailingPathDelimiter(FDatabaseTargetDir))));
  OleCheck(Task.SetAccountInformation('', nil)); // run as local system

  FillChar(TriggerData, SizeOf(TriggerData), 0);
  TriggerData.cbTriggerSize := SizeOf(TriggerData);
  TriggerData.wBeginYear := YearOf(Today);
  TriggerData.wBeginMonth := MonthOf(Today);
  TriggerData.wBeginDay := DayOf(Today);
  TriggerData.wStartHour := 0;
  TriggerData.wStartMinute := 0;
  TriggerData.rgFlags := 0;
  TriggerData.TriggerType := TASK_TIME_TRIGGER_DAILY;
  TriggerData.Type_.Daily.DaysInterval := 1;

  OleCheck(Task.CreateTrigger(TriggerIndex, Trigger));
  OleCheck(Trigger.SetTrigger(@TriggerData));

  TaskPersist := Task as IPersistFile;
  OleCheck(TaskPersist.Save(nil, True));
end;

procedure TSetupDataModule.RemoveDatabaseBackupTask;
var
  Scheduler: ITaskScheduler;
begin
  OleCheck(CoCreateInstance(CLSID_CTaskScheduler, nil, CLSCTX_INPROC_SERVER, IID_ITaskScheduler, Scheduler));
  OleCheck(Scheduler.Delete(BackupTaskName));
end;