WMI: Win32 _ Service has a StartService method. This is good for cases where you need to be able to perform other processing (e.g. to select which service).
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();
}
}
}
Just a note: You might have set up your service differently using the forms interface to add a service installer and project installer. In that case replace where it says serviceInstaller.ServiceName with "name from designer".ServiceName.
using System.ServiceProcess;
[RunInstaller(true)]
public partial class ProjectInstaller : System.Configuration.Install.Installer
{
public ProjectInstaller()
{
InitializeComponent(); //generated code including property settings from previous steps
this.serviceInstaller1.AfterInstall += Autorun_AfterServiceInstall; //use your ServiceInstaller name if changed from serviceInstaller1
}
void Autorun_AfterServiceInstall(object sender, InstallEventArgs e)
{
ServiceInstaller serviceInstaller = (ServiceInstaller)sender;
using (ServiceController sc = new ServiceController(serviceInstaller.ServiceName))
{
sc.Start();
}
}
}
This is OK for me. In Service project add to Installer.cs
[RunInstaller(true)]
public partial class ProjectInstaller : System.Configuration.Install.Installer
{
public ProjectInstaller()
{
InitializeComponent();
}
protected override void OnAfterInstall(IDictionary savedState)
{
base.OnAfterInstall(savedState);
//The following code starts the services after it is installed.
using (System.ServiceProcess.ServiceController serviceController = new System.ServiceProcess.ServiceController(serviceInstaller1.ServiceName))
{
serviceController.Start();
}
}
}