How to start my Windows Service at RunTime or at OnAfterInstall

强颜欢笑 提交于 2019-12-12 03:53:55

问题


History

I am building a Windows Service as part of my Platform Application to handle updates and server functions, so it can be installed in machines different than where the Client Application is installed. It uses UDP to send and receive broadcast messages, and TCP to to handle more sensitive and most important messages.

Objective

I want that my Application could be easily installed by the end user, just by copying the executable files in the computers and when executing them. The main application should verify if the user is an administrator, create the configuration files, and then install the Windows Service and run it, so when non administrative users log in, they won't receive any error from my Application regarding administrative rights. The goal is to make most configurations without the need a present technician, since database will be remote.

Problem

My Service is being installed normally with the command MyService.exe /install but it is not starting automatically. The only way to start it is to go on Control Panel > Admin Tools > Services and do it manually. I tryed to call net start MyService through my application but I receive invalid service name at the shell. I tryied the executable name, the display name and the object name of the service, but none of them worked. This is the object of my TService:

object ServiceMainController: TServiceMainController
  OldCreateOrder = False
  OnCreate = ServiceCreate
  DisplayName = 'PlatformUpdateService'
  Interactive = True
  AfterInstall = ServiceAfterInstall
  AfterUninstall = ServiceAfterUninstall
  OnShutdown = ServiceShutdown
  OnStart = ServiceStart
  OnStop = ServiceStop
  Height = 210
  Width = 320 

Question

What should I do to start my service by the code and not by the user hands? It would be the best if I could do it inside my client application, or when by itself after the OnServiceAfterInstall call.


回答1:


Here's a sample StartService call, in AfterInstall event:

procedure TServiceMainController.ServiceAfterInstall(Sender: TService);
var
  Manager, Service: SC_HANDLE;
begin
  Manager := OpenSCManager(nil, nil, SC_MANAGER_ALL_ACCESS);
  Win32Check(Manager <> 0);
  try
    Service := OpenService(Manager, PChar(Name), SERVICE_ALL_ACCESS);
    Win32Check(Service <> 0);
    try
      Win32Check(StartService(Service, 0, PChar(nil^)));
    finally
      CloseServiceHandle(Service);
    end;
  finally
    CloseServiceHandle(Manager);
  end;
end;

However I'm not sure it will work for you, as normally you should have success with net start too.



来源:https://stackoverflow.com/questions/18324174/how-to-start-my-windows-service-at-runtime-or-at-onafterinstall

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!