Windows服务安装后自动启动

在服务上添加安装程序,在serviceProcessInstaller1控件的Committed事件当中添加代码:

            System.ServiceProcess.ServiceController     controller     =     new     System.ServiceProcess.ServiceController("MyService");  
            controller.Start();  

MyService为服务名


此操作之前要先设置下两个控件

设置serviceProcessInstaller1控件的Account属性为“LocalSystem
设置serviceInstaller1控件的StartType属性为"Automatic"

 

以上代码有误,待解决后再修改

----------------华丽的分割线--------------------------

在服务器上添加安装程序,在private void ProjectInstaller_AfterInstall(object sender, InstallEventArgs e)事件中,添加以下代码:

 

Process p = new Process();
p.StartInfo.FileName 
= "cmd.exe";
p.StartInfo.UseShellExecute 
= false;
p.StartInfo.RedirectStandardInput 
= true;
p.StartInfo.RedirectStandardOutput 
= true;
p.StartInfo.RedirectStandardError 
= true;
p.StartInfo.CreateNoWindow 
= true;
p.Start();
string Cmdstring = "sc start myservice"//CMD命令
p.StandardInput.WriteLine(Cmdstring);
p.StandardInput.WriteLine(
"exit");

即可在安装服务后立刻启动windows服务

 

注: 引用using System.Diagnostics;//调用Process

 

以上代码,亲测成功! 欢迎点评(在网上找了n久解决方案,最后还是自己搞定,转载请注明出处)

posted @ 2009-01-14 10:40  风w  阅读(4815)  评论(3编辑  收藏  举报