5

我已经使用 Delphi 提供了服务。每次我在该服务中调用另一个应用程序时,该应用程序都没有运行。怎么了?

顺便说一句,我使用过 shellexecute、shellopen 或用 cmd 调用它。这些方法都不起作用。

这是我的代码:

    program roro_serv;

uses
  SvcMgr,
  Unit1 in 'Unit1.pas' {Service1: TService},
  ping in 'ping.pas';

{$R *.RES}

begin
  Application.Initialize;
  Application.CreateForm(TService1, Service1);
  Application.Run;
end.

    unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, SvcMgr, Dialogs,
  ExtCtrls, DB, MemDS, DBAccess, MyAccess, Menus, forms, IniFiles,
  ComCtrls, wininet, Variants, shellapi,
  FileCtrl, ExtActns, StdCtrls, ShellCtrls;

type
  TService1 = class(TService)
    Timer1: TTimer;
    procedure Timer1Timer(Sender: TObject);
    procedure ServiceExecute(Sender: TService);
    procedure ServiceStop(Sender: TService; var Stopped: Boolean);
    procedure ServiceStart(Sender: TService; var Started: Boolean);
  private
    { Private declarations }
  public
    function GetServiceController: TServiceController; override;
    { Public declarations }
    procedure run_procedure;
    procedure log(text_file, atext : string );
    procedure loginfo(text : string);
    function  CheckUrl(url: string): boolean;
    procedure execCMD(CommandLine, Work:  string);
    function  DoDownload(FromUrl, ToFile: String): boolean;
  end;

var
  Service1: TService1;
  iTime : integer;
  limit_time : integer = 2;
  myini : TiniFile;
  default_exe_path : string = '';
  default_log_path : string = '';
  appdir : String = '';

implementation

{$R *.DFM}

uses ping;

function TService1.CheckUrl(url: string): boolean;
var 
hSession, hfile, hRequest: hInternet;
dwindex,dwcodelen :dword; 
dwcode:array[1..20] of char; 
res : pchar; 
begin 
if pos('http://',lowercase(url))=0 then 
url := 'http://'+url; 
Result := false; 
hSession := InternetOpen('InetURL:/1.0', 
INTERNET_OPEN_TYPE_PRECONFIG,nil, nil, 0);
if assigned(hsession) then
begin 
hfile := InternetOpenUrl(
hsession, 
pchar(url), 
nil, 
0, 
INTERNET_FLAG_RELOAD, 
0); 
dwIndex := 0; 
dwCodeLen := 10; 
HttpQueryInfo(hfile, HTTP_QUERY_STATUS_CODE, 
@dwcode, dwcodeLen, dwIndex); 
res := pchar(@dwcode); 
result:= (res ='200') or (res ='302'); 
if assigned(hfile) then 
InternetCloseHandle(hfile); 
InternetCloseHandle(hsession); 
end;
end;

procedure ServiceController(CtrlCode: DWord); stdcall;
begin
  Service1.Controller(CtrlCode);
end;

function TService1.GetServiceController: TServiceController;
begin
  Result := ServiceController;
end;

procedure TService1.Timer1Timer(Sender: TObject);
begin
iTime:=iTime+1;
if iTime=15 then // (limit_time*60) then
  begin
      itime:=1;
      run_procedure;
  end;
// loginfo('Defaultlog : '+default_log_path+'; exe : '+default_exe_path);
end;

procedure TService1.ServiceExecute(Sender: TService);
begin
Timer1.Enabled := True;
while not Terminated do
ServiceThread.ProcessRequests(True);
Timer1.Enabled := False;
end;

procedure TService1.run_procedure;
var
i : integer;
sUrl, sLogFile, sAction, sAct_param : String;
begin
for i:=0 to 20 do
   begin
   sLogFile:=default_log_path+myini.ReadString('logs', 'log_file'+intTostr(i), '');
   if fileexists(slogfile) then
      begin
      loginfo(slogfile+' tersedia');
      sAction:=myini.ReadString('logs', 'action'+intTostr(i), '');
           if ((trim(sAction)<>'') and (fileexists(default_exe_path+sAction))) then
              begin
                   // this line is don't work in servcie
                   ShellExecute(Application.Handle, 'open', 'c:\Windows\notepad.exe', nil, nil, SW_SHOWNORMAL);
                   sAct_param:=myini.ReadString('logs', 'action_prm'+intTostr(i), '');
                   // this line is don't work in servcie
                   execCMD(sAction+' '+sAct_param, default_exe_path);
                   loginfo(sAction+' '+sAct_param+' defpath : '+default_exe_path);
                   // this loginfo works
              end;
      end else
      begin

      end;

   end;
end;

procedure TService1.log(text_file, atext: string);
var
logFile : TextFile;
begin
AssignFile(LogFile, text_file);
if FileExists(text_file) then
Append(LogFile) else rewrite(LogFile);
WriteLn(logFile, aText);
CloseFile(LogFile);
end;

procedure TService1.loginfo(text: string);
begin
log(ChangeFileExt(application.exename, '.log'), formatdateTime('dd-mm-yyyy hh:nn:ss ', now)+
text);
end;

procedure TService1.ServiceStop(Sender: TService; var Stopped: Boolean);
begin
myini.Free;
end;

procedure TService1.execCMD(CommandLine, Work: string);
var
SA: TSecurityAttributes;
SI: TStartupInfo;
PI: TProcessInformation;
StdOutPipeRead, StdOutPipeWrite: THandle;
WorkDir: string;
begin
with SA do begin
nLength := SizeOf(SA);
bInheritHandle := True;
lpSecurityDescriptor := nil;
end;
CreatePipe(StdOutPipeRead, StdOutPipeWrite, @SA, 0);
try
with SI do
begin
FillChar(SI, SizeOf(SI), 0);
cb := SizeOf(SI);
dwFlags := STARTF_USESHOWWINDOW or STARTF_USESTDHANDLES;
wShowWindow := SW_HIDE;
hStdInput := GetStdHandle(STD_INPUT_HANDLE); // don't redirect stdin
hStdOutput := StdOutPipeWrite;
hStdError := StdOutPipeWrite;
end;
WorkDir := Work;
CreateProcess(nil, PChar('cmd.exe /C ' + CommandLine),
nil, nil, True, 0, nil,
PChar(WorkDir), SI, PI);
CloseHandle(StdOutPipeWrite);
finally
CloseHandle(StdOutPipeRead);
end;
end;

procedure TService1.ServiceStart(Sender: TService; var Started: Boolean);
begin
appdir:=ExtractFileDir(Application.ExeName);
myini:=TiniFile.Create(ExtractFileDir(application.ExeName)+'\setting.ini');
limit_time:=myini.ReadInteger('setting', 'limit_time', 0);
default_exe_path:=myini.ReadString('setting', 'default_exe_path','');
if trim(default_exe_path)='' then default_exe_path:=appdir+'\';

default_log_path:=myini.ReadString('setting', 'default_log_path','');
if trim(default_log_path)='' then default_log_path:=appdir+'\logs\';

end;

function TService1.DoDownload(FromUrl, ToFile: String): boolean;
begin
 {  with TDownloadURL.Create(self) do
   try
     URL:=FromUrl;
     FileName := ToFile;
     ExecuteTarget(nil) ;
   finally
     Free;
   end;    }
end;

end.

请参阅 run_procedure 代码行;

简而言之:如何从我的服务中调用另一个应用程序?

4

3 回答 3

10

ShellExecute/Ex()CreateProcess()在与调用进程相同的会话中运行指定的文件/应用程序。服务始终在会话 0 中运行。

在 XP 和更早版本中,第一个登录的用户也在会话 0 中运行,因此服务可以运行交互式进程并让该交互式用户查看它,但前提是该服务被标记为交互式(TService.Interactive属性为 true)。如果多个用户登录,他们在会话 1+ 中运行,因此看不到服务运行的交互式进程。

Windows Vista 引入了一项名为“Session 0 Isolation”的新功能。交互式用户根本不再在会话 0 中运行,而是始终在会话 1+ 中运行,会话 0 根本不是交互式的(该TService.Interactive属性不再有任何作用)。但是,为了帮助迁移遗留服务,如果服务运行尝试在会话 0 上显示 GUI 的交互式进程,Windows 会提示当前登录的用户(如果有)切换到临时使 GUI 可见的单独桌面. 在 Windows 7 及更高版本中,该旧版支持现已不复存在。

从 2000 年开始,在 Windows 上的所有版本中,从服务运行交互式进程并使其对交互式用户可见的正确方法是使用CreateProcessAsUser()在指定用户的会话和桌面中运行新进程。MSDN、StackOverflow 和整个 Web 上都有很多详细的示例,所以我不打算在这里重复它们。

于 2013-02-10T19:46:09.453 回答
5

服务在与交互式用户不同的会话中运行。服务在会话 0 中运行。会话 0 进程无权访问交互式桌面。这意味着在会话 0 中显示交互式进程的任何尝试都注定要失败。您正在尝试创建一个交互式记事本进程。

有多种方法可以通过会话在交互式桌面上启动进程:在 Windows Vista 和更高版本中从 Windows 服务启动交互式进程。正如您在阅读那篇文章后会理解的那样,您尝试做的事情并非易事。

于 2013-02-10T19:32:44.537 回答
2

此解决方案旨在从服务中使用,我想我会在此处粘贴此代码,因为它是我让我的服务以当前登录用户身份运行应用程序的方式。

function WTSQueryUserToken(SessionId: ULONG; var phToken: THandle): BOOL; stdcall; external 'Wtsapi32.dll';

procedure runApp(appName: String);
var
  hToken: THandle;
  StartupInfo: TStartupInfo;
  ProcessInfo: TProcessInformation;
  res: boolean;

  begin
    GetStartupInfo(StartupInfo);
   if WTSQueryUserToken(WtsGetActiveConsoleSessionID, hToken) then
   begin
     res := CreateProcessAsUser(hToken, PWideChar(appName), nil, nil, nil, False, CREATE_NEW_CONSOLE, nil, nil, StartupInfo, ProcessInfo);
     if res then
      WaitForSingleObject(ProcessInfo.hProcess,INFINITE);
   end;
end;

//您的服务或应用程序中的任何位置

RunApp ('notepad.exe');
于 2018-08-10T10:49:31.387 回答