问题
I install a service in windows server 2008 r2 , and want to start it when windows start
class Program : ServiceBase
{
...
static void Main(string[] args)
{
ServiceBase.Run(new Program());
}
public Program()
{
this.ServiceName = "ABPS";
}
protected override void OnStart(string[] args)
{
base.OnStart(args);
this.start();//a method that start works
}
...
回答1:
you should add installer to your application.
To determine how your service will be started, click the ServiceInstaller component and set the StartType property to the appropriate value.
- Manual The service must be manually started after installation.
- Automatic The service will start by itself whenever the computer reboots.
- Disabled The service cannot be started.
you can start your service in AfterInstall
event handler
void ServiceInstaller_AfterInstall(object sender, InstallEventArgs e)
{
using (ServiceController sc = new ServiceController(serviceInstaller.ServiceName))
{
sc.Start();
}
}
回答2:
You'll need to add an installer to your Service application, where you will need to set the StartType property.
http://msdn.microsoft.com/en-us/library/ddhy0byf%28v=VS.90%29.aspx
serviceInstaller.StartType = ServiceStartMode.Automatic;
来源:https://stackoverflow.com/questions/27456460/start-service-automatically-when-windows-start