windows服务状态自动启动

很多人制作成Windows服务安装包时发现明明在属性里面设置了自动启动,可在服务安装完成以后,还需要手动启动服务,我这里有一种完全实现自动启动的方法

在ProjectInstaller.cs 文件做文章就行,直接代码如下:

 

 1 public partial class ProjectInstaller : System.Configuration.Install.Installer
 2     {
 3         public ProjectInstaller()
 4         {
 5             InitializeComponent();
 6             //设置安装后自动启动
 7             this.AfterInstall += new InstallEventHandler(ProjectInstaller_AfterInstall);
 8         }
 9         /// <summary>
10         /// 设置安装后自动启动
11         /// serviceInstaller1 中的StartType要设置成Automatic,表示随机启动,
12         /// ServiceName表示服务名称,
13         /// Description 表示服务的描述, 
14         /// DisplayName 表示显示名称。
15         /// serviceProcessInstaller1 中的Account要设置成LocalSystem,表示本地系统帐号        
16         /// </summary>
17         /// <param name="sender"></param>
18         /// <param name="e"></param>
19         private void ProjectInstaller_AfterInstall(object sender, InstallEventArgs e)
20         {
21             Process p = new Process();
22             p.StartInfo.FileName = "cmd.exe";
23             p.StartInfo.UseShellExecute = false;
24             p.StartInfo.RedirectStandardInput = true;
25             p.StartInfo.RedirectStandardOutput = true;
26             p.StartInfo.RedirectStandardError = true;
27             p.StartInfo.CreateNoWindow = true;
28             p.Start();
29             string Cmdstring = "sc start JieService"; //CMD命令    JieService服务名称
30             p.StandardInput.WriteLine(Cmdstring);
31             p.StandardInput.WriteLine("exit");
32         }
33     }
View Code

注意:在代码中,“JieService”这个是服务名称。一定记得改,很容易忽略掉

posted on 2016-04-12 17:08  UnLike  阅读(1106)  评论(0编辑  收藏  举报

导航