How to make a .NET Windows Service start right after the installation?

前端 未结 8 1591
再見小時候
再見小時候 2020-11-22 10:49

Besides the service.StartType = ServiceStartMode.Automatic my service does not start after installation

Solution

Inserted this code on my Pr

8条回答
  •  暖寄归人
    2020-11-22 11:39

    To add to ScottTx's answer, here's the actual code to start the service if you're doing it the Microsoft way (ie. using a Setup project etc...)

    (excuse the VB.net code, but this is what I'm stuck with)

    Private Sub ServiceInstaller1_AfterInstall(ByVal sender As System.Object, ByVal e As System.Configuration.Install.InstallEventArgs) Handles ServiceInstaller1.AfterInstall
        Dim sc As New ServiceController()
        sc.ServiceName = ServiceInstaller1.ServiceName
    
        If sc.Status = ServiceControllerStatus.Stopped Then
            Try
                ' Start the service, and wait until its status is "Running".
                sc.Start()
                sc.WaitForStatus(ServiceControllerStatus.Running)
    
                ' TODO: log status of service here: sc.Status
            Catch ex As Exception
                ' TODO: log an error here: "Could not start service: ex.Message"
                Throw
            End Try
        End If
    End Sub
    

    To create the above event handler, go to the ProjectInstaller designer where the 2 controlls are. Click on the ServiceInstaller1 control. Go to the properties window under events and there you'll find the AfterInstall event.

    Note: Don't put the above code under the AfterInstall event for ServiceProcessInstaller1. It won't work, coming from experience. :)

提交回复
热议问题