C#开发WINDOWS服务 简单实例!!!
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace TestService
{
public partial class CareEye : ServiceBase
{
private Thread MainThread;
// private System.ComponentModel.Container components = null;
public CareEye()
{
InitializeComponent();
// TODO: 在 InitComponent 调用后添加任何初始化
MainThread=new Thread(new ThreadStart(ThreadFunc));
MainThread.Priority=ThreadPriority.Lowest;
}
// 进程的主入口点
//static void Main()
//{
// //System.ServiceProcess.ServiceBase[] ServicesToRun;
// // 同一进程中可以运行多个用户服务。若要将
// //另一个服务添加到此进程,请更改下行
// // 以创建另一个服务对象。例如,
// //
// // ServicesToRun = New System.ServiceProcess.ServiceBase[] {new CareEye(), new MySecondUserService()};
// //
// //ServicesToRun = new System.ServiceProcess.ServiceBase[] { new CareEye() };
// System.ServiceProcess.ServiceBase.Run(new CareEye());
//}
protected override void OnStart(string[] args)
{
// TODO: 在此处添加代码以启动服务。
MainThread.Start();
}
protected override void OnStop()
{
// TODO: 在此处添加代码以执行停止服务所需的关闭操作。
MainThread.Abort();
}
public static void ThreadFunc()
{
int LastHour = DateTime.Now.Hour;
while (true)
{
System.Threading.Thread.Sleep(60000);
if (DateTime.Now.Hour - 1 == LastHour)
{
MessageBox.Show("为了爱护您的眼睛,请您暂时休息5分钟并向远处眺望!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly);
LastHour = DateTime.Now.Hour;
}
}
}
}
}