How to add a scheduled task on network connection/disconnection event with Inno Setup

孤者浪人 提交于 2019-12-01 13:53:02

As with any other obscure scheduling settings, you have to use XML definition of the task.

The easiest is to configure the task in Windows Task Scheduler GUI, select the created task and choose Export command.

It will create an XML definition of the task, which will contain something like:

<?xml version="1.0" encoding="UTF-16"?>
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
  <!-- ... -->
  <Triggers>
    <EventTrigger>
      <Enabled>true</Enabled>
      <Subscription>&lt;QueryList&gt;&lt;Query Id="0" Path="Microsoft-Windows-NetworkProfile/Operational"&gt;&lt;Select Path="Microsoft-Windows-NetworkProfile/Operational"&gt;*[System[Provider[@Name='NetworkProfile'] and EventID=10000]]&lt;/Select&gt;&lt;/Query&gt;&lt;/QueryList&gt;</Subscription>
    </EventTrigger>
  </Triggers>
  <!-- ... -->
</Task>

Edit the XML to remove everything, what is specific to your computer.

And then use the exported XML as a template for a file, that you will create on the fly in the installer with an actual path to your installed application:

[Run]
Filename: "schtasks.exe"; \
    Parameters: "/Create /TN MyTask /XML ""{tmp}\Task.xml"""; \
    StatusMsg: "Scheduling task..."; Flags: runhidden; BeforeInstall: CreateTaskXml

[Code]

procedure CreateTaskXml;
var
  TaskXml: string;
begin
  TaskXml :=
    '<?xml version="1.0"?>' + #13#10 +
    '<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">'
      + #13#10 +
    '  <Triggers>' + #13#10 +
    { The EventTrigger here }
    '  </Triggers>' + #13#10 +
    { ... }
    '  <Actions Context="Author">' + #13#10 +
    '    <Exec>' + #13#10 +
    '      <Command>' + ExpandConstant('{app}\MyProg.exe') + '</Command>' + #13#10 +
    '    </Exec>' + #13#10 +
    '  </Actions>' + #13#10 +
    '</Task>' + #13#10;

  if SaveStringToFile(ExpandConstant('{tmp}\Task.xml'), TaskXml, False) then
  begin
    Log('Task XML successfully created');
  end
    else
  begin
    Log('Failed to create task XML');
  end;
end;

The SaveStringToFile function in CreateTaskXml creates the XML in Ansi encoding. If you need Unicode, you have to create the XML in UTF-16 encoding (schtasks does not support UTF-8).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!