1. 建立空白项目
2.添加创建windows服务需要的引用,选择System.ServiceProcess。
3.创建服务类,继承ServiceBase,类的源代码在后面。
4. 添加windows服务的安装类。
(1)在类名或者解决方案中新建视图:
(2)上一步后会出来类的视图,右键选择查看设计器:
(3)在设计视图里面添加安装器(有可能会弹出警告框,如图,不用管):
5 服务类源代码:
1 using System; 2 using System.Collections.Generic; 3 using System.IO; 4 using System.Linq; 5 using System.Text; 6 using System.Threading.Tasks; 7 using System.Timers; 8 9 namespace SR171 10 { 11 class Service17: System.ServiceProcess.ServiceBase 12 { 13 14 public Service17()//可以自己设定 15 { 16 this.ServiceName = "MyServiceForShowTime"; 17 this.CanStop = true; 18 this.CanPauseAndContinue = true; 19 this.AutoLog = true; 20 21 #region 定时器事件 22 Timer aTimer = new Timer(); //System.Timers,不是form的 23 aTimer.Elapsed += new ElapsedEventHandler(TimedEvent); 24 aTimer.Interval = 2 * 1000; //配置文件中配置的秒数 25 aTimer.Enabled = true; 26 #endregion 27 } 28 public static void Main()//必须写 29 { 30 System.ServiceProcess.ServiceBase.Run(new Service17()); 31 } 32 protected override void OnStart(string[] args)//自己根据要求覆写 33 { 34 FileStream fs = new FileStream(@"d:\mcWindowsService.txt", FileMode.OpenOrCreate, FileAccess.Write); 35 36 StreamWriter m_streamWriter = new StreamWriter(fs); 37 38 m_streamWriter.BaseStream.Seek(0, SeekOrigin.End); 39 40 m_streamWriter.WriteLine("mcWindowsService: Service Started" + DateTime.Now.ToString() + "\n"); 41 42 m_streamWriter.Flush(); 43 44 m_streamWriter.Close(); 45 46 fs.Close(); 47 48 49 } 50 protected override void OnStop() 51 { 52 53 FileStream fs = new FileStream(@"d:\mcWindowsService.txt", FileMode.OpenOrCreate, FileAccess.Write); 54 55 StreamWriter m_streamWriter = new StreamWriter(fs); 56 57 m_streamWriter.BaseStream.Seek(0, SeekOrigin.End); 58 59 m_streamWriter.WriteLine(" mcWindowsService: Service Stopped " + DateTime.Now.ToString() + "\n"); 60 61 m_streamWriter.Flush(); 62 63 m_streamWriter.Close(); 64 65 fs.Close(); 66 67 } 68 69 70 private static void TimedEvent(object source, ElapsedEventArgs e) //运行期间执行 71 { 72 FileStream fs = new FileStream(@"d:\mcWindowsService.txt", FileMode.OpenOrCreate, FileAccess.Write); 73 74 StreamWriter m_streamWriter = new StreamWriter(fs); 75 76 m_streamWriter.BaseStream.Seek(0, SeekOrigin.End); 77 78 m_streamWriter.WriteLine(" Running.11.. " + DateTime.Now.ToString() + "\n"); 79 80 m_streamWriter.Flush(); 81 82 m_streamWriter.Close(); 83 84 fs.Close(); 85 } 86 87 } 88 }