zoukankan      html  css  js  c++  java
  • Windows服务安装完成后自动启动

    public ServiceInstaller()
    {
        //... Installer code here
        this.AfterInstall += new InstallEventHandler(ServiceInstaller_AfterInstall);
    }
    
    void ServiceInstaller_AfterInstall(object sender, InstallEventArgs e)
    {
        using (ServiceController sc = new ServiceController(serviceInstaller.ServiceName))
        {
             sc.Start();
        }
    }
    
    注意配置为本地服务和自动启动模式。。。

    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 Start Type of Manual 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(); } } }

    这种通过进程 命令的方式也行,但是不太好

    /// <summary>
            /// 安装后自动启动服务
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void ProjectInstaller_AfterInstall(object sender, InstallEventArgs e)
            {
                Process p = new Process
                {
                    StartInfo =
                    {
                        FileName = "cmd.exe",
                        UseShellExecute = false,
                        RedirectStandardInput = true,
                        RedirectStandardOutput = true,
                        RedirectStandardError = true,
                        CreateNoWindow = true
                    }
                };
                p.Start();
                const string cmdString = "sc start 你的服务名称"; //cmd命令, 服务的名称
                p.StandardInput.WriteLine(cmdString);
                p.StandardInput.WriteLine("exit");
            }
  • 相关阅读:
    养兔引起轩然大波,做事情执着的他竟做到了年产值3000万元
    凭良心用好料,做卫生包子让他的日营业收入近3000元
    肉牛养殖前景好,他尝到甜头带富了贫困户
    那些年,我们处理过的SQL问题
    windows右键没有新建选项的解决办法
    windows右键没有新建选项的解决办法
    IT服务,共享经济的下一个风口?
    IT服务,共享经济的下一个风口?
    IT服务,共享经济的下一个风口?
    IT服务,共享经济的下一个风口?
  • 原文地址:https://www.cnblogs.com/micro-chen/p/5576810.html
Copyright © 2011-2022 走看看