In your Installer class, add a handler for the AfterInstall event. You can then call the ServiceController in the event handler to start the service.
using System.ServiceProcess;
public ServiceInstaller()
{
//... Installer code here
this.AfterInstall += new InstallEventHandler(ServiceInstaller_AfterInstall);
}
void ServiceInstaller_AfterInstall(object sender, InstallEventArgs e)
{
ServiceInstaller serviceInstaller = (ServiceInstaller)sender;
using (ServiceController sc = new ServiceController(serviceInstaller.ServiceName))
{
sc.Start();
}
}
Now when you run InstallUtil on your installer, it will install and then start up the service automatically.
After refactoring a little bit, this is an example of a complete windows service installer with automatic start:
using System.ComponentModel;
using System.Configuration.Install;
using System.ServiceProcess;
namespace Example.of.name.space
{
[RunInstaller(true)]
public partial class ServiceInstaller : Installer
{
private readonly ServiceProcessInstaller processInstaller;
private readonly System.ServiceProcess.ServiceInstaller serviceInstaller;
public ServiceInstaller()
{
InitializeComponent();
processInstaller = new ServiceProcessInstaller();
serviceInstaller = new System.ServiceProcess.ServiceInstaller();
// Service will run under system account
processInstaller.Account = ServiceAccount.LocalSystem;
// Service will have Automatic Start Type
serviceInstaller.StartType = ServiceStartMode.Automatic;
serviceInstaller.ServiceName = "Windows Automatic Start Service";
Installers.Add(serviceInstaller);
Installers.Add(processInstaller);
serviceInstaller.AfterInstall += ServiceInstaller_AfterInstall;
}
private void ServiceInstaller_AfterInstall(object sender, InstallEventArgs e)
{
ServiceController sc = new ServiceController("Windows Automatic Start Service");
sc.Start();
}
}
}
How about following commands?
net start "<service name>"
net stop "<service name>"
Programmatic options for controlling services:
StartService
method. This is good for cases where you need to be able to perform other processing (e.g. to select which service).Start-Service
via RunspaceInvoke
or by creating your own Runspace
and using its CreatePipeline
method to execute. This is good for cases where you need to be able to perform other processing (e.g. to select which service) with a much easier coding model than WMI, but depends on PSH being installed.ServiceController
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With