Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
?
Solved

NT Service

Posted on 2003-03-03
4
Medium Priority
?
623 Views
Last Modified: 2010-04-04
Hi all,

How can I write a NT Service (That will work on WinXP too) ?, and how can I start and stop this service from with my Application.

Thank you
0
Comment
Question by:PieterJ
  • 2
4 Comments
 
LVL 1

Accepted Solution

by:
SimesA earned 400 total points
ID: 8062866
To write a service, run Delphi, select File -> New... -> Service. Write handlers for the TService.OnStart and OnStop events.


To control a service use the Service Control Manager...
program ServiceStartStop;

uses
  Windows,
  SysUtils,
  WinSvc;

{$R *.RES}

procedure ReportMessage(const Msg: string);
begin
  WriteLn(Output, msg);
end;

procedure ReportLastError(const Msg: string);
var
  code: integer;
begin
  code := GetLastError;
  ReportMessage(Format('%s, error code %d (0x%x)', [msg, code, code]));
end;

function StateToText(const State: Dword): string;
begin
  if state = SERVICE_STOPPED then
    result := 'stopped'
  else if state = SERVICE_START_PENDING then
    result := 'start pending'
  else if state = SERVICE_STOP_PENDING then
    result := 'stop pending'
  else if state = SERVICE_RUNNING then
    result := 'running'
  else if state = SERVICE_CONTINUE_PENDING then
    result := 'continue pending'
  else if state = SERVICE_PAUSE_PENDING then
    result := 'pause pending'
  else if state = SERVICE_PAUSED then
    result := 'paused'
  else
    result := 'unknown state';
end;

var
  ServiceName: string;
  StartStop: string;
  MgrHandle, SvcHandle: SC_HANDLE;
  ptr: pchar;
  ServiceStatus: TServiceStatus;
  EnumServiceStatus: array[0..999] of TEnumServiceStatus;
  numbytes, numservices, ResumeHandle, i: dword;
begin
  StartStop := Uppercase(ParamStr(1));
  ServiceName := ParamStr(2);
  if (StartStop <> 'START') and (StartStop <> 'STOP') and (StartStop <> 'LIST') then begin
    ReportMessage('Unrecognised or missing parameter, specify START, STOP or LIST as the first parameter');
    exit;
  end;
  if (StartStop <> 'LIST') and (ServiceName = '') then begin
    ReportMessage('Missing parameter, specify the service name as the second parameter');
    exit;
  end;

  mgrhandle := OpenSCManager(nil, nil, GENERIC_EXECUTE or SC_MANAGER_ENUMERATE_SERVICE);
  if mgrhandle <> 0 then begin
    if StartStop = 'LIST' then begin
      ResumeHandle := 0;
      if EnumServicesStatus(mgrhandle, SERVICE_WIN32 or SERVICE_DRIVER, SERVICE_ACTIVE or SERVICE_INACTIVE, EnumServiceStatus[0], sizeof(EnumServiceStatus), numbytes, numservices, ResumeHandle) then begin
        for i := 0 to pred(numservices) do
          with EnumServiceStatus[i] do
            ReportMessage('Service name "' + lpServiceName + '", display name "' + lpDisplayName + '", state "' + StateToText(ServiceStatus.dwCurrentState) + '"');
      end else
        ReportLastError('Unable to list services');
    end else begin
      svchandle := OpenService(mgrhandle, pchar(ServiceName), GENERIC_EXECUTE);
      if svchandle = 0 then begin
        // couldn't open the service - see if the user specified a "Display Name" rather than a "Service Name"
        ResumeHandle := 0;
        if EnumServicesStatus(mgrhandle, SERVICE_WIN32 or SERVICE_DRIVER, SERVICE_ACTIVE or SERVICE_INACTIVE, EnumServiceStatus[0], sizeof(EnumServiceStatus), numbytes, numservices, ResumeHandle) then begin
          for i := 0 to pred(numservices) do
            with EnumServiceStatus[i] do
              if CompareText(lpDisplayName, ServiceName) = 0 then begin
                svchandle := OpenService(mgrhandle, lpServiceName, GENERIC_EXECUTE);
                break;
              end;
        end else
          ReportLastError('Unable to enumerate services');
      end;
      if svchandle <> 0 then begin
        ptr := nil;
        if StartStop = 'START' then begin
          if StartService(svchandle, 0, ptr) then
            ReportMessage(ServiceName + ' service started')
          else
            ReportLastError('Unable to start service');
        end else if StartStop = 'STOP' then begin
          if ControlService(svchandle, SERVICE_CONTROL_STOP, ServiceStatus) then
            ReportMessage(ServiceName + ' service stopped')
          else
            ReportLastError('Unable to stop service');
        end;
        CloseServiceHandle(svchandle);
      end else begin
        ReportLastError('Unable to open service ' + ServiceName);
//        ListServices(mgrhandle);
      end;
    end;
    CloseServiceHandle(mgrhandle);
  end else
    ReportLastError('Unable to open service manager');
end.


0
 
LVL 12

Expert Comment

by:Lee_Nover
ID: 8064224
to control the service it's simplest to use TSrvCtrl v2.2
free for noncommecial usage
http://homepages.borland.com/torry/nt.htm
0
 
LVL 12

Expert Comment

by:Lee_Nover
ID: 8064232
also check their home page : http://www.gsc.hu/index.php?lang=en
0
 
LVL 2

Expert Comment

by:cqhall
ID: 9367196
I found this on the Delphi SuperPage.  http://delphi.icm.edu.pl/ftp/d20free/vpcsrvce.zip.  I is freeware and includes source, although it claims support through D4.

"NT Service Wrapper. A form that replace the main application form, to create an NT service having to only write one line of code
--------------------------------------------------------------------------------
Added: 13-09-1998   |  Version: n/a   |  Downloads: 5289/5289/0
--------------------------------------------------------------------------------
Author: Peter Spears"



Chuck Hall
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Objective: - This article will help user in how to convert their numeric value become words. How to use 1. You can copy this code in your Unit as function 2. than you can perform your function by type this code The Code   (CODE) The Im…
Introduction The parallel port is a very commonly known port, it was widely used to connect a printer to the PC, if you look at the back of your computer, for those who don't have newer computers, there will be a port with 25 pins and a small print…
Integration Management Part 2
Screencast - Getting to Know the Pipeline

581 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question