Automatically start a Windows Service on install

前端 未结 13 1339
轻奢々
轻奢々 2020-11-28 19:13

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

13条回答
  •  隐瞒了意图╮
    2020-11-28 19:49

    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.

提交回复
热议问题