title: Console Application Install as Service
body: <p>I'm looking and trying to install my console application as service but not figured out how to do it.  </p>
  
  <p>any recommendation ? </p>
  
  <p>actually i just wanted to install as service and start automatically each time windows starts or delay start</p>
  
  <pre><code>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.
  </code></pre>