Automatically start a Windows Service on install

前端 未结 13 1371
轻奢々
轻奢々 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:48

    Here is a procedure and code using generated ProjectInstaller in Visual Studio:

    1. Create Windows Service project in Visual Studio
    2. Generate installers to the service
    3. Open ProjectInstaller in design editor (it should open automatically when installer is created) and set properties of generated serviceProcessInstaller1 (e.g. Account: LocalSystem) and serviceInstaller1 (e.g. StartType: Automatic)
    4. Open ProjectInstaller in code editor (press F7 in design editor) and add event handler to ServiceInstaller.AfterInstall - see the following code. It will start the service after its installation.

    ProjectInstaller class:

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

提交回复
热议问题