c# - 双击启动 Windows 服务

标签 c# windows-services autostart

如何使我的 Windows 服务以下列方式工作...

1.) 安装后自动启动

2.) 即使我们简单地双击可执行文件也会自动启动

换句话说,我不想使用“NET START”、“SC”命令,也不想通过服务控制台启动它。我只希望我的服务能够自动安装并自动启动......加上双击可执行文件时自动启动。

谢谢。

最佳答案

看看ServiceController类。

您可以在 commited 中使用它像这样的事件:

[RunInstaller(true)]
public class ServiceInstaller : Installer
{
    string serviceName = "MyServiceName";

    public ServiceInstaller()
    {
        var processInstaller = new ServiceProcessInstaller();
        var serviceInstaller = new ServiceInstaller();

        processInstaller.Account = ...;
        processInstaller.Username = ...;
        processInstaller.Password = ...;

        serviceInstaller.DisplayName = serviceName;
        serviceInstaller.StartType = ServiceStartMode.Automatic;

        serviceInstaller.ServiceName = serviceName;

        this.Installers.Add(processInstaller);
        this.Installers.Add(serviceInstaller);

        this.Committed += new InstallEventHandler(ServiceInstaller_Committed);
    }

    void ServiceInstaller_Committed(object sender, InstallEventArgs e)
    {
        // Auto Start the Service Once Installation is Finished.
        var controller = new ServiceController(serviceName);
        controller.Start();
    }
}

关于c# - 双击启动 Windows 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3171987/

相关文章:

c# - 如何更改 android 和 ios 中开关的颜色?

c# - NHibernate 连接 + 合并

c# - 如果 Windows 服务停止,给我发电子邮件

c# - 在没有打印对话框的情况下从 Windows 服务打印 html 文档

c - 在系统启动时在 Yocto MiniDisplay 上打印

linux - Electron :linux start at boot up system

c# - OpenXML 读取 CustomXMLPart

c# - 强制 WaitCursor 到模态窗体的父窗体

python - 编写每 5 分钟执行一次的 python 脚本

c# - RabbitMQ 消费者