首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在安装时自动启动Windows服务

在安装时自动启动Windows服务
EN

Stack Overflow用户
提问于 2009-06-24 06:33:09
回答 10查看 109.8K关注 0票数 123

我有一个使用InstallUtil.exe安装的Windows Service。即使我已将Startup Method设置为Automatic,但服务在安装时不会启动,我必须手动打开服务并单击start。有没有办法通过命令行或通过服务的代码来启动它?

EN

回答 10

Stack Overflow用户

回答已采纳

发布于 2009-06-25 09:55:37

在Installer类中,为AfterInstall事件添加一个处理程序。然后,您可以在事件处理程序中调用ServiceController来启动服务。

代码语言:javascript
复制
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();
    }
}

现在,当您在安装程序上运行InstallUtil时,它将自动安装并启动服务。

票数 228
EN

Stack Overflow用户

发布于 2011-07-13 19:05:45

在稍微重构之后,这是一个完整的具有自动启动功能的windows服务安装程序的示例:

代码语言:javascript
复制
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();
    }
}
}
票数 30
EN

Stack Overflow用户

发布于 2009-06-24 06:37:49

下面的命令怎么样?

代码语言:javascript
复制
net start "<service name>"
net stop "<service name>"
票数 8
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1036713

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档