1
using
System;
2 using System.Collections.Generic;
3 using System.ComponentModel;
4 using System.Data;
5 using System.Diagnostics;
6 using System.ServiceProcess;
7 using System.Text;
8 using System.Windows.Forms;
9 using System.Threading;
10
11 namespace EyeService
12 {
13 public partial class EyeService : ServiceBase
14 {
15 private Thread MainThread;
16
17 public EyeService()
18 {
19 InitializeComponent();
20 MainThread = new Thread(new ThreadStart(ThreadFunc));
21 MainThread.Priority = ThreadPriority.Lowest;
22 }
23
24 protected override void OnStart(string[] args)
25 {
26 // TODO: 在此处添加代码以启动服务。
27 MainThread.Start();
28 }
29
30 protected override void OnStop()
31 {
32 // TODO: 在此处添加代码以执行停止服务所需的关闭操作。
33 MainThread.Abort();
34 }
35 /**//// <summary>
36 /// 保护方法
37 /// </summary>
38 public static void ThreadFunc()
39 {
40 int LastHour = DateTime.Now.Hour;
41 while (true)
42 {
43 System.Threading.Thread.Sleep(60000);
44 if (DateTime.Now.Hour - 1 == LastHour)
45 {
46 MessageBox.Show("为了保护您的眼睛,请您暂时休息5分钟并向远处眺望!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly);
47 LastHour = DateTime.Now.Hour;
48 }
49 }
50 }
51 }
52}
添加安装程序,将serviceInstaller1启动类型改为:Automatic以便开机即运行此服务.其他属性根据个人爱好更改即可.最后安装下此服务后,在控制面板的服务列表中就可以看到了.2 using System.Collections.Generic;
3 using System.ComponentModel;
4 using System.Data;
5 using System.Diagnostics;
6 using System.ServiceProcess;
7 using System.Text;
8 using System.Windows.Forms;
9 using System.Threading;
10
11 namespace EyeService
12 {
13 public partial class EyeService : ServiceBase
14 {
15 private Thread MainThread;
16
17 public EyeService()
18 {
19 InitializeComponent();
20 MainThread = new Thread(new ThreadStart(ThreadFunc));
21 MainThread.Priority = ThreadPriority.Lowest;
22 }
23
24 protected override void OnStart(string[] args)
25 {
26 // TODO: 在此处添加代码以启动服务。
27 MainThread.Start();
28 }
29
30 protected override void OnStop()
31 {
32 // TODO: 在此处添加代码以执行停止服务所需的关闭操作。
33 MainThread.Abort();
34 }
35 /**//// <summary>
36 /// 保护方法
37 /// </summary>
38 public static void ThreadFunc()
39 {
40 int LastHour = DateTime.Now.Hour;
41 while (true)
42 {
43 System.Threading.Thread.Sleep(60000);
44 if (DateTime.Now.Hour - 1 == LastHour)
45 {
46 MessageBox.Show("为了保护您的眼睛,请您暂时休息5分钟并向远处眺望!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly);
47 LastHour = DateTime.Now.Hour;
48 }
49 }
50 }
51 }
52}
运行一小时后弹出信息框: