?
Solved

NT Service

Posted on 2003-03-03
4
Medium Priority
?
615 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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

On Demand Webinar: Networking for the Cloud Era

Did you know SD-WANs can improve network connectivity? Check out this webinar to learn how an SD-WAN simplified, one-click tool can help you migrate and manage data in the cloud.

Question has a verified solution.

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

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…
Have you ever had your Delphi form/application just hanging while waiting for data to load? This is the article to read if you want to learn some things about adding threads for data loading in the background. First, I'll setup a general applica…
In this video we outline the Physical Segments view of NetCrunch network monitor. By following this brief how-to video, you will be able to learn how NetCrunch visualizes your network, how granular is the information collected, as well as where to f…
In this brief tutorial Pawel from AdRem Software explains how you can quickly find out which services are running on your network, or what are the IP addresses of servers responsible for each service. Software used is freeware NetCrunch Tools (https…
Suggested Courses

800 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