C# 使用windown服务使 程序开机自动运行(不需登录到桌面)

 最近有这么个需求,要求程序不登陆桌面就自动运行。通过查找资料,有三种方式:

1.修改注册表,这个不能用,能实现自启 但要登录到桌面;

2.计划任务程序,这个按道理能实现,不过我没实现的了;

3.windown服务,这个就是我要说的, 刚查资料了解;

 

首先新建一个“windown服务”项目, 在生成的 service1的OnStart中编写要执行的程序:

View Code
 1 using System;
 2 using System.Collections.Generic;
 3 using System.ComponentModel;
 4 using System.Data;
 5 using System.Diagnostics;
 6 using System.Linq;
 7 using System.ServiceProcess;
 8 using System.Text;
 9 
10 namespace WindowsService1
11 {
12     public partial class Service1 : ServiceBase
13     {
14         public Service1()
15         {
16             InitializeComponent();
17         }
18 
19         protected override void OnStart(string[] args)
20         {
21             string strPath = @"F:\web\netFrom\thread\test\bin\Debug\test.exe";
22 
23             try
24             {
25                 Process proc = new Process();
26                 proc.StartInfo.FileName = strPath; //启动路径  
27                 proc.Start();
28 
29             }
30             catch (Exception e)
31             {
32                 
33             }
34         }
35 
36         protected override void OnStop()
37         {
38         }
39     }
40 }

然后在service设计中右击 添加安装程序 会生成 ProjectInstaller文件 在它的Designer.cs文件的 InitializeComponent()方法中 添加:

1  this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.LocalSystem;
2             this.serviceInstaller1.ServiceName = "test";     //我的服务名称
3             this.serviceInstaller1.StartType = System.ServiceProcess.ServiceStartMode.Automatic; //服务自动运行

 

最后一步 在cmd中安装一下 就ok了

1.先找到 InstallUtil.exe ;  我的是在 C:\Windows\Microsoft.NET\Framework\v4.0.30319  后面这个v4.0.30319是4.0版本的fw,其他版本的进入相应的文件就行了

2.在cmd 中 cd C:\Windows\Microsoft.NET\Framework\v4.0.30319 先进入这文件 ; 然后安装   InstallUtil  @path   //@path是windown服务的exe执行文件

3.卸载  InstallUtil  /u  @path

没什么意外的话 就能开机自启了

 

 

posted @ 2013-05-07 16:36  冰vs焰  阅读(860)  评论(0)    收藏  举报