Solved

delphi and TService

Posted on 2009-04-06
6
2,301 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 36

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
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
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 36

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

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
for loop with Set 4 45
mapBully challenge 6 89
How to renew a Delphi rad-studio licence? 5 33
Delphi inherited method 6 40
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Although it can be difficult to imagine, someday your child will have a career of his or her own. He or she will likely start a family, buy a home and start having their own children. So, while being a kid is still extremely important, it’s also …
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…

706 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

19 Experts available now in Live!

Get 1:1 Help Now