VS2010 创建 windows service 程序

参考网上保护眼睛程序,自写程序如下。

1、创建一个名词为“CareEyeService”,类型为“WindowsService”的应用程序。

自动生成代码如下图:

2、修改ServiceCareEye.cs的代码

public partial class ServiceCareEye : ServiceBase
{
private Thread MainThread;

public ServiceCareEye()
{
InitializeComponent();
MainThread = new Thread(new ThreadStart(thredFunc));
MainThread.Priority = ThreadPriority.Lowest;
}

protected override void OnStart(string[] args)
{
MainThread.Start();
}

protected override void OnStop()
{
if (MainThread.ThreadState == System.Threading.ThreadState.Running)
{
MainThread.Abort();
}
}

public void thredFunc()
{
int lastHour = DateTime.Now.Hour;
while (true)
{
Thread.Sleep(60000);
if (DateTime.Now.Hour - 1 == lastHour)
{
MessageBox.Show("为了您的眼睛的健康,请您闭眼休息5分钟或者远眺5分钟", "警告",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
lastHour = DateTime.Now.Hour;
}
}
}
}

3、修改ServiceCareEye服务的设计视图,右键“添加安装程序”,如图:

4、为设置服务的登陆账号密码,如果不想设置用户名密码也可以采用本地系统帐户运行服务,代码如下

this.serviceInstaller1.StartType = System.ServiceProcess.ServiceStartMode.Automatic;

至此创建完成。

安装和卸载Windows服务

制作完成的Windows服务发布后是一个exe文件,要想在使用的机器上启用这个服务,我们要用微软提供的工具Installutil工具,利用命令行安装和卸载此服务。

installutil工具在目录:系统盘:\WINDOWS\Microsoft.NET\Framework\v4.0.30319下,运行cmd,输入:C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\installutil xxxx.exe 回车,即可完成windows服务的安装。

卸载则为输入 C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\installutil /u xxxx.exe 回车。

安装之后运行windowservice服务时有时可能会遇到service会自动down掉得情况,这种情况有肯能是编译时的exe文件是x64或者x86的情况,所以我们用mubuild手动build成anycpu的exe服务,可能会得到解决。

实例:

C:\Windows\Microsoft.NET\Framework\v4.0.30319>InstallUtil.exe E:\congrixu\demo\

CareEyeService\CareEyeService\bin\Debug\CareEyeService.exe

posted on 2015-09-18 12:40  编程笑笑生  阅读(250)  评论(0编辑  收藏  举报

导航