控制台应用安装为服务

use*_*395 3 delphi delphi-7

我正在寻找并尝试安装我的控制台应用程序作为服务,但没有想出如何做到这一点.

任何建议?

实际上我只想安装为服务,并在每次启动或延迟启动时自动启动

program Project1;

  Uses
  Windows,
  SysUtils,
  Dialogs,
  Messages,TlHelp32,Classes, Graphics, Controls, SvcMgr,ExtCtrls;

 Const
  SECURITY_NT_AUTHORITY: TSIDIdentifierAuthority = (Value: (0, 0, 0, 0, 0, 5));
  SECURITY_BUILTIN_DOMAIN_RID = $00000020;
  DOMAIN_ALIAS_RID_ADMINS = $00000220;

  type
  TService1 = class(TService)
  private
  public
    function GetServiceController: TServiceController; override;
  end;


  var
  Service1: TService1;
  Msg: TMsg;

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


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

Function IsAdmin: Boolean;
var
  hAccessToken: THandle;
  ptgGroups: PTokenGroups;
  dwInfoBufferSize: DWORD;
  psidAdministrators: PSID;
  x: Integer;
  bSuccess: BOOL;
begin
  Result   := False;
  bSuccess := OpenThreadToken(GetCurrentThread, TOKEN_QUERY, True,
    hAccessToken);
  if not bSuccess then
  begin
    if GetLastError = ERROR_NO_TOKEN then
      bSuccess := OpenProcessToken(GetCurrentProcess, TOKEN_QUERY,
        hAccessToken);
  end;
  if bSuccess then
  begin
    GetMem(ptgGroups, 1024);
    bSuccess := GetTokenInformation(hAccessToken, TokenGroups,
      ptgGroups, 1024, dwInfoBufferSize);
    CloseHandle(hAccessToken);
    if bSuccess then
    begin
      AllocateAndInitializeSid(SECURITY_NT_AUTHORITY, 2,
        SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS,
        0, 0, 0, 0, 0, 0, psidAdministrators);
      {$R-}
      for x := 0 to ptgGroups.GroupCount - 1 do
        if EqualSid(psidAdministrators, ptgGroups.Groups[x].Sid) then
        begin
          Result := True;
          Break;
        end;
      {$R+}
      FreeSid(psidAdministrators);
    end;
    FreeMem(ptgGroups);
  end;
end;

begin

 if IsAdmin then
   begin
                 // Install me as service 
   end else
 begin
    ShowMessage('Not Running As Admin');
 end;


  while GetMessage(Msg, 0, 0, 0) do
   begin
   TranslateMessage(Msg);
   DispatchMessage(Msg);
  end;

end.
Run Code Online (Sandbox Code Playgroud)

Dav*_*vid 5

至少有两种方式:其中一种是'正确'方式,一种是'错误'(但有效).

错误但有效的方式

您可以通过(主机)帮助程序实用程序将任何应用程序作为服务运行,例如:

为什么这是错误的方式?因为如果您希望应用程序作为服务运行,则应创建服务应用程序.事实上,使用Delphi非常容易.这是正确的方法:

正确的方法:创建一个服务应用程序

这篇delphi.about.com文章有很多关于服务应用程序的信息.但是,它非常简单:通过File> New> [也许Other>] Service Application创建一个新的服务应用程序.设置显示名称等.要安装它,请使用命令行开关运行/install; 卸载运行/uninstall.

如果您希望命令行应用程序作为服务运行的原因是您不想编写两个应用程序,那么设计良好可以最大限度地减少额外的工作.在您的项目组中有两个应用程序,即命令行应用程序和服务应用程序.然后在其他文件中共享代码 - 即编写代码以执行应用程序的工作一次,并从两个项目中包含/调用它.