Automatically start a Windows Service on install

mickyjtwin picture mickyjtwin · Jun 24, 2009 · Viewed 102.9k times · Source

I have a Windows Service which I install using the InstallUtil.exe. Even though I have set the Startup Method to Automatic, the service does not start when installed, I have to manually open the services and click start. Is there a way to start it either via the command line, or through the code of the Service?

Answer

codemonkey picture codemonkey · Jun 25, 2009

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.