Automatically start a Windows Service on install

前端 未结 13 1372
轻奢々
轻奢々 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条回答
  •  旧时难觅i
    2020-11-28 19:37

    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();
        }
    }
    }
    

提交回复
热议问题