Solved

delphi and TService

Posted on 2009-04-06
6
2,306 Views
Last Modified: 2012-05-06
Hi Experts

I'm trying to create a service in delphi, but is not working. I am using delphi 7 and windows xp professional.

What's wrong with this code

Alexandre
unit Unit1;
 

interface
 

uses

  Windows, Messages, SysUtils, Classes, Graphics, Controls, SvcMgr, Dialogs,

  ExtCtrls;
 

type

  TService1 = class(TService)

    Timer1: TTimer;

    procedure ServiceExecute(Sender: TService);

    procedure Timer1Timer(Sender: TObject);

  private

    { Private declarations }

  public

    function GetServiceController: TServiceController; override;

    { Public declarations }

  end;
 

var

  Service1: TService1;
 

implementation
 

{$R *.DFM}
 

procedure ServiceController(CtrlCode: DWord); stdcall;

begin

  Service1.Controller(CtrlCode);

end;
 

function TService1.GetServiceController: TServiceController;

begin

  Result := ServiceController;

end;
 

procedure TService1.ServiceExecute(Sender: TService);

begin

  Timer1.Enabled := True;

  while not Terminated do

  ServiceThread.ProcessRequests(True);

  Timer1.Enabled := False;

end;
 

procedure TService1.Timer1Timer(Sender: TObject);

const

  FileName = 'c:\logdate.txt';

var

  F: TextFile;

begin

  AssignFile(f,FileName);

  if FileExists(FileName) then Append(f)

  else

  Rewrite(f);

  writeln(f,DateTimeToStr(Now));

  ShowMessage(DateTimeToStr(Now));

  CloseFile(f);

end;
 

end.

Open in new window

0
Comment
Question by:alpires
6 Comments
 
LVL 37

Expert Comment

by:Geert Gruwez
ID: 24081890
how are you trying to run this ?

you need to run it from the cmd prompt

service.exe /install
0
 

Author Comment

by:alpires
ID: 24082243
Yes I'm doing this, but still not working
0
 

Author Comment

by:alpires
ID: 24083670
Well, Now I made these changes and worked:

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

But now i have some questions:

1- How star the service by another delphi
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 13

Accepted Solution

by:
ThievingSix earned 250 total points
ID: 24084081
You mean like this:

ShellExecute(0,'open','C:\myservice.exe','/install','',SW_SHOWNORMAL);

0
 
LVL 12

Assisted Solution

by:Hypo
Hypo earned 250 total points
ID: 24084458
To start and stop services programatically, you have to use the ServiceControlManager. You can read all about it in the Win32 SDK help. What you do is that you allocate a handle to the ServiceControlManager, from which you can then request a handle to the service you want to start, by calling OpenService and providing the service name as a parameter. When you have a handle to the service, you can call the function StartService to Start; or ControlService with parameter SERVICE_CONTROL_STOP to stop the service. The service needs to be installed on your computer for this to work.

The example I've provided below uses the default service database on the local computer, which is where I assume your service will exist, but you can also connect to other databases or other computers by submitting the correct parameters to the OpenSCManager call.

Create an application with two buttons and a TEdit, and then add the code I've provided below. Button1 will start the service named by Edit1, and Button2 will stop the service.

regards
Hypo
Procedure StartService(ServiceName : AnsiString; Const Args : Array of String);

var i : Integer;

    sArgs : String;

    sFirst : PAnsiChar;

    aServiceControl : SC_Handle;

    aService : SC_Handle;

begin

  aService := 0;

  // Get a handle to the service manager...

  aServiceControl := WinSVC.OpenSCManager(nil, nil, SC_MANAGER_CONNECT);

  if aServiceControl = 0 then RaiseLastOSError;

  try

    // Get a handle to the service...

    aService := WinSVC.OpenService(aServiceControl, PAnsiChar(ServiceName), SERVICE_START);

    if aService = 0 then RaiseLastOSError;

    // Build sArgs string by concatenating the Args elemtents, separated by #0

    for i := 0 to Length(Args)-1

      do sArgs := sArgs + Args[i] + #0;

    // Point to the first String...

    if Length(sArgs) > 0

      then sFirst := Addr(sArgs[1])

      else sFirst := nil;

    // try Starting the service...

    if not WinSVC.StartService(aService, Length(Args), sFirst)

      then RaiseLastOSError;

  finally

    if aService <> 0 then WinSVC.CloseServiceHandle(aService);

    if aServiceControl <> 0 then WinSVC.CloseServiceHandle(aServiceControl)

  end;

End;
 

Procedure StopService(ServiceName : AnsiString);

var aServiceControl : SC_Handle;

    aService : SC_Handle;

    aStatus : TServiceStatus;

begin

  aService := 0;

  // Get a handle to the service manager...

  aServiceControl := WinSVC.OpenSCManager(nil, nil, SC_MANAGER_CONNECT);

  if aServiceControl = 0 then RaiseLastOSError;

  try

    // Get a handle to the service...

    aService := WinSVC.OpenService(aServiceControl, PAnsiChar(ServiceName), SERVICE_STOP);

    if aService = 0 then RaiseLastOSError;

    // try Stopping the service...

    if not WinSVC.ControlService(aService, SERVICE_CONTROL_STOP, aStatus)

      then RaiseLastOSError;

  finally

    if aService <> 0 then WinSVC.CloseServiceHandle(aService);

    if aServiceControl <> 0 then WinSVC.CloseServiceHandle(aServiceControl)

  end;

End;
 

procedure TForm1.Button1Click(Sender: TObject);

begin

  // You can pass runparameters to the service here...

  // Ex: StartService(Edit1.Text, ['MyRunParam1', 'MyRunParam2']);

  StartService(Edit1.Text, []);

end;
 

procedure TForm1.Button2Click(Sender: TObject);

begin

  StopService(Edit1.Text);

end;

Open in new window

0
 
LVL 37

Expert Comment

by:Geert Gruwez
ID: 24084460
to start it from the Delphi Ide :

Add "/Install" to the Parameters Edit in Menu Run / Parameters / Tab Local

And hit Run (F9)

0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
groupSumClump challenge 9 98
Eclipse Neon start with Admin account only 6 91
Unique identifier on a terminal server (rdp) 4 45
Full Screen problem when auto scale IFRAME 2 60
Introduction Raise your hands if you were as upset with FireMonkey as I was when I discovered that there was no TListview.  I use TListView in almost all of my applications I've written, and I was not going to compromise by resorting to TStringGrid…
A short article about problems I had with the new location API and permissions in Marshmallow
In this fourth video of the Xpdf series, we discuss and demonstrate the PDFinfo utility, which retrieves the contents of a PDF's Info Dictionary, as well as some other information, including the page count. We show how to isolate the page count in a…
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…

914 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

Need Help in Real-Time?

Connect with top rated Experts

23 Experts available now in Live!

Get 1:1 Help Now