1. 新建一个项目
2. 从一个可用的项目模板列表当中选择Windows服务
3. 设计器会以设计模式打开
4. 工具箱->右键->选择项->system.timers.timer确定然后将该Timer拖到窗体上
5. 设置Timer属性,Interval属性1000毫秒
6. 然后为这个服务填加功能
7.双击这个Timer,然后在里面写代码,比如
[
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;
using System.IO;
namespace myservice
{
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
}
public int i = 0;
StreamWriter sw = new StreamWriter("c:\\a.txt", true);
protected override void OnStart(string[] args)
{
// TODO: Add code here to start your service.
timer1.Interval = 1000;
timer1.Enabled = true;
timer1.Start();
}
protected override void OnStop()
{
// TODO: Add code here to perform any tear-down necessary to stop your service.
//System.Diagnostics.Process.Start("explorer.exe", "http://www.google.com");
//timer1.Enabled = true;
//sw.Close();
return;
OnStart(null);
}
private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
sw.Write(i);
sw.Flush();
i++;
if(i>200)
{
sw.Close();
timer1.Enabled = true;
}
}
}
}
]
8. 将这个服务程序切换到设计视图
9. 右击设计视图选择“添加安装程序”
10. 切换到刚被添加的ProjectInstaller的设计视图
11. 设置serviceInstaller1组件的属性:
1) ServiceName = My Sample Service
2) StartType = Automatic (开机自动运行)
12. 设置serviceProcessInstaller1组件的属性 Account = LocalSystem
13. 改变路径到你项目所在的bin\Debug文件夹位置(如果你以Release模式编译则在bin\Release文件夹)
14. 执行命令“InstallUtil MyWindowsService.exe”注册这个服务,使它建立一个合适的注册项。(InstallUtil这个程序在WINDOWS文件夹\Microsoft.NET\Framework\v1.1.4322下面)
15. 右击桌面上“我的电脑”,选择“管理”就可以打计算机管理控制台
16. 在“服务和应用程序”里面的“服务”部分里,你可以发现你的Windows服务已经包含在服务列表当中了
17. 右击你的服务选择启动就可以启动你的服务了 ,看看你c盘下的a.txt文件是不是每秒都在增加数字啊(F5刷新看效果)